views:

15

answers:

1

I'm using Entity Framework 4 and having trouble with a query.

I have two objects:

Instruction Component

Between these objects there's a many-to-many relation. An Instruction van point to one or more Components. And a Component can be referenced by multiple Instructions.

I am trying to get how many 'finished' (status = 6) Instructions there are for each Component.

In SQL this is easy:

select c.id, COUNT(*)
from Component c
inner join InstructionComponents ic on c.Id = ic.Component_Id
inner join Instructions i on i.Id = ic.Instruction_Id
where i.StatusValue = 6
group by c.id

I'm having trouble doing this in EF. This is what I've tried:

var result =
   from component in Copmponents
   where component.Instructions.Any(s => s.Status == 6)
   group component by component.Id
   into componentGroup
   select new { compId = onderdeelGroup.Key, count = componentGroup.Count() };

But his query doesn't return the correct count. I don't know how the count the number of instructions.

+1  A: 

How about this?

var query = Components.Select(c => new 
            { 
                c.Id, 
                Count = c.Instructions.Count(i => i.Status == 6)
            });
tzaman
Ok, this is the solution. Thank you very much!!Looks easy. It took me way too long.
Thomas
You're welcome! :)
tzaman
Actually, just remembered Count has a predicate version too, so you can collapse the Where clause into it - edited to be even more concise.
tzaman