Linq to Entities with Subselect in select part

こ雲淡風輕ζ 提交于 2019-12-11 02:39:06

问题


We are starting with a MVC project using EF. We will need write a lot of queries in LINQ using subselect and don't have figured out yet how this could be done.

The most simple case of these is in this form:

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

Reading the "101 page" of examples from Microsoft and Stack Overflow I couldn't find a example like this. I found examples using join and group, but in some cases the are already a group in the query.

Can you help me with this query, please? Thanks.


回答1:


You will need a Navigation property called Comments on Post (EF automatically creates it if you have foreign keys specified) then you can use query as under.

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


来源:https://stackoverflow.com/questions/7754058/linq-to-entities-with-subselect-in-select-part

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!