3

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?

Cœur
  • 32,421
  • 21
  • 173
  • 232
roeland
  • 4,973
  • 5
  • 39
  • 57

2 Answers2

3

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()
    }
Pranay Rana
  • 164,177
  • 33
  • 228
  • 256
  • 1
    This is indeed a shorter version of the linq query, but the problem is that I cannot project onto a mapped entity. – roeland Aug 24 '11 at 12:25
0

I worked around this by using annonymous types.

roeland
  • 4,973
  • 5
  • 39
  • 57