Count + group +, where

I am using Entity Framework 4 and have query issues.

I have two objects:

Instruction Component

Between these objects there is a many-to-many relationship. The command manager points to one or more Components. And the Component can be referenced by several instructions.

I am trying to get how many "ready" (status = 6) instructions 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 am having problems with this in EF. This is what I 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 does not return the correct score. I do not know how to count the number of instructions.

+3
source share
1 answer

How about this?

var query = Components.Select(c => new 
            { 
                c.Id, 
                Count = c.Instructions.Count(i => i.Status == 6)
            });
+5
source

Source: https://habr.com/ru/post/1754198/


All Articles