LINQ-左联接,分组依据和计数

假设我有以下SQL:

SELECT p.ParentId, COUNT(c.ChildId)

FROM ParentTable p

LEFT OUTER JOIN ChildTable c ON p.ParentId = c.ChildParentId

GROUP BY p.ParentId

如何将其转换为LINQ to SQL?我被困在COUNT(c.ChildId),生成的SQL似乎总是输出COUNT(*)。这是到目前为止我得到的:

from p in context.ParentTable

join c in context.ChildTable on p.ParentId equals c.ChildParentId into j1

from j2 in j1.DefaultIfEmpty()

group j2 by p.ParentId into grouped

select new { ParentId = grouped.Key, Count = grouped.Count() }

谢谢!

回答:

from p in context.ParentTable

join c in context.ChildTable on p.ParentId equals c.ChildParentId into j1

from j2 in j1.DefaultIfEmpty()

group j2 by p.ParentId into grouped

select new { ParentId = grouped.Key, Count = grouped.Count(t=>t.ChildId != null) }

以上是 LINQ-左联接,分组依据和计数 的全部内容, 来源链接: utcz.com/qa/400121.html

回到顶部