LINQ到与子查询实体在选择部分 [英] Linq to Entities with Subselect in select part
问题描述
我们已经开始使用EF一个MVC项目。 我们需要使用子查询在LINQ中写了很多的查询,并且没有想出但如何能够做到这一点。
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';
读101页的微软和堆栈溢出的例子我找不到这样的例子。 我发现采用加入和组的例子,但在某些情况下,已经是组中的查询。
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.
推荐答案
您需要叫上发表评论导航属性(如果有指定的外键EF自动创建它),那么你可以使用查询作为下。
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()
}
这篇关于LINQ到与子查询实体在选择部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!