【问题标题】:Linq to Entities count subquery?Linq to Entity count 子查询?
【发布时间】:2011-08-24 12:02:16
【问题描述】:

我正在尝试在 linq 中对实体 (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

还有其他方法吗?

【问题讨论】:

  • 是听者,deatil 有任何一对多的关系吗?
  • 是的,一对多(一个标题,多个细节)
  • @Roeland 想明白了吗?

标签: c# linq entity-framework


【解决方案1】:

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

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

【讨论】:

  • 这确实是 linq 查询的较短版本,但问题是我无法投影到映射实体上。
【解决方案2】:

我通过使用匿名类型解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-24
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    相关资源
    最近更新 更多