Linq to Entities with Subselect 在选择部分

Linq to Entities with Subselect in select part(Linq to Entities with Subselect 在选择部分)
本文介绍了Linq to Entities with Subselect 在选择部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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';

阅读 Microsoft 和 Stack Overflow 的101 页"示例,我找不到这样的示例.我找到了使用 join 和 group 的示例,但在某些情况下,它们已经是查询中的一个组.

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.

推荐答案

您将需要一个名为 Comments on Post 的 Navigation 属性(如果您指定了外键,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 to Entities with Subselect 在选择部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)