2017-06-18 82 views
0

我正在使用LINQ从数据库中获取记录,我已经在SQL服务器上编写了一个SQL查询,我正在使用asp.net .NET MVC编写LINQ查询,我正在使用由左组的加入,并在查询次数所以说,它不具有范围变量的选择,我已经尝试了很多东西,但失败了,以下是查询通过左连接使用组和LINQ计数

SQL查询:

select Post_ID, Post, com.cmtcount from Posts left join (select Comments.postID, 
Count(Comments.comments) as cmtcount from Comments group by postID) 
as com on com.postID = Post_ID; 

Linq查询:

from row in db.Posts join cmtrow in db.Comments on row.Post_ID 
equals cmtrow.postID into ps from cmtrow in ps.DefaultIfEmpty() 
    group cmtrow by cmtrow.Comments_ID into grouped select new 
{ row.Post1, row.Posted_by,cmtrow.comments, 
count = grouped.Count(t=>t.Comments_ID!=null) }; 

回答

1

我会写SQL查询这样的:

SELECT 
     p.Post_ID 
    , p.Post 
    , COUNT(c.CommentID) as cmtcount 
FROM Posts p 
    LEFT JOIN Comments c ON c.PostID = p.Post_ID 
GROUP BY p.Post_ID, p.Post 

在LINQ,你可以写这样的事情:

from p in db.Posts 
join c in db.Comments on p.Post_ID equals c.PostID into commentsInPost 
select new 
{ 
    PostId = p.Post_ID, 
    Post = p.Post1, 
    cmtcount = commentsInPost.Count() 
}; 

通过LinQ中生成的SQL如下:

SELECT 
    [Extent1].[Post_ID] AS [Post_ID], 
    [Extent1].[Post] AS [Post], 
    (SELECT 
     COUNT(1) AS [A1] 
     FROM [dbo].[Comments] AS [Extent2] 
     WHERE [Extent1].[Post_ID] = [Extent2].[PostID]) AS [C1] 
FROM [dbo].[Posts] AS [Extent1] 

两种SQL语法都是正确的,并且会返回相同的结果,由您决定使用哪一个。