Linq to Entities count subquery?
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 queryIs 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.
精彩评论