问题
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