选择部分中具有子选择的实体的Linq

Jua*_*atz 2 .net linq entities subquery

我们从使用EF的MVC项目开始。我们将需要使用subselect在LINQ中编写很多查询,但还没有弄清楚如何做到这一点。

这些中最简单的情况是这种形式:

select p.Id, 
       p.Title,
       (select count(*) 
          from Comments c
         where c.PostId = p.Id
       ) as CommentCount
  from Post p
 where p.UserId = 'John';
Run Code Online (Sandbox Code Playgroud)

从Microsoft和Stack Overflow阅读示例的“ 101页”,我找不到这样的示例。我发现了使用join和group的示例,但是在某些情况下,查询中已经是一个组。

您能帮我这个疑问吗?谢谢。

Muh*_*han 5

您将需要一个导航属性,即“评论后发表”(如果您指定了外键,EF将自动创建该属性),然后您可以按以下方式使用查询。

from p in Context.Posts
where p.UserId == "John"
select new 
{
  Id = p.Id,
  Title = p.Title,
  Count = p.Comments.Count()
}
Run Code Online (Sandbox Code Playgroud)