c# - Linq to Entities 计数子查询?

标签 c# linq entity-framework

我正在尝试在 linq to entities (EF4) 中执行此查询

select Header.Id, 
 (select count(*) 
  from Detail 
  where Header.Id = Detail.headerId) detailcount
from Header

这行不通,因为它在 EF 中是不允许的:
(Header 和 Detail 是 EntityObjects)

from h in context.Header
select new Header
    {
        Id = h.Id,
        DetailCount = (from d in context.Detail 
                       where d.headerId = p.Id select d).Count()
    }

DetailCount是我在Detail Entity(分部类)上新增的属性

上面的 Linq 查询不起作用,因为我无法投影到映射的实体上:
The entity cannot be constructed in a LINQ to Entities query

还有其他方法吗?

最佳答案

下面将为您完成任务,因为两者都是相关实体

from h in context.Header
select new Header
    {
        Id = h.Id,
        detailCount = h.Detail.Count()
    }

关于c# - Linq to Entities 计数子查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7175081/

相关文章:

c# - 在 Generic 中实现接口(interface)时,为什么它不是必须实现方法

c# - 如何在多个项目中使用 useLegacyV2RuntimeActivationPolicy?

c# - 与数组相比,使用 IEnumerable 有哪些优势?

c# - 使用 linq 截断文本

c# - 在 C# 中合并字符串中的相似字符

c# - Visual Studio MVC 5 显示错误但编译和运行正常

c# - Null Dapper.net 查询仍然使用 FirstOrDefault() 返回 Null Reference Exception

c# - 使用 Entity Framework 时发生内存泄漏

c# - 如何在 IQueryable<> 中选择日期间隔?

entity-framework - 带有标识列的 EF Code First 父子插入