Using LINQ to Entities I'm having trouble getting a count of child objects given a list of parent ids. Here's how I'd do it in straight SQL:
SELECT COUNT(Child.ParentId) ,Parent.Parentd
FROM Parent
LEFT OUTER JOIN Child ON Child.ParentId = Parent.ParentId
WHERE
Parent.ParentId IN (
8417
,118458
,120567
,121596
)
GROUP BY Parent.ParentId
Here's what I've tried in LINQ to Entities:
var counts = from Parent in context.Parents
join Child in context.Children on Parent.ParentId equals Child.ParentId
into children
from jn in children.DefaultIfEmpty()
where iEnumerableParentIds.Contains(parent.parentId)
group parent by parent.parentId
into g
select new {count = g.Count(), parentId = g.Key};
This is pretty close but I'm counting the grouped parent instead of the child which gives me a count of 1 when there are no children on the parent.