开发者

Linq to Entities count subquery?

开发者 https://www.devze.com 2023-03-30 22:46 出处:网络
I\'m trying to do this query in linq to entities (EF4) select Header.Id, (select count(*) from Detail

I'm trying to do this query in linq to entities (EF4)

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

This won't work because it's not allowed in EF:

(Header and Detail are 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 is a new property I added on the Detail Entity (partial class)

The above Linq query doesn't work because I cannot project onto a mapped entity:

The entity cannot be constructed in a LINQ to Entities query

Is there an other way of开发者_如何学编程 doing this?


below will do you task because both are related entities

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


I worked around this by using annonymous types.

0

精彩评论

暂无评论...
验证码 换一张
取 消