我正在使用LINQ从数据库中获取记录,我在SQL服务器上编写了一个SQL查询,我在asp .net MVC中编写LINQ查询,我使用group by left join并count in查询所以它说它在select中没有范围变量,我尝试了很多但是失败了,以下是查询
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) };
答案 0 :(得分: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语法都是正确的,并且会返回相同的结果,由您决定使用哪一种。