2017-06-18 81 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語法都是正確的,並且會返回相同的結果,由您決定使用哪一個。