LINQ - 左加入,集团通过和Count集团、LINQ、Count

2023-09-02 01:18:32 作者:毕业那天跟校长撕名牌

让我们说我有这个SQL语句:

  SELECT p.ParentId,COUNT(c.ChildId)
从ParentTable p
  LEFT OUTER JOIN ChildTable C对p.ParentId = c.ChildParentId
GROUP BY p.ParentId
 

我怎样才能把它理解的LINQ to SQL?我被困在COUNT(c.ChildId),生成的SQL似乎总是输出COUNT(*)。以下是我有这么远:

 由对在context.ParentTable
加入c。在context.ChildTable上p.ParentId等于c.ChildParentId到J1
从J2在j1.DefaultIfEmpty()
一群J2通过p.ParentId到分组
选择新{的ParentId = grouped.Key,计数= grouped.Count()}
 
2019年全球奢侈品公司排行榜 最新

感谢您!

解决方案

 由对在context.ParentTable
加入c。在context.ChildTable上p.ParentId等于c.ChildParentId到J1
从J2在j1.DefaultIfEmpty()
一群J2通过p.ParentId到分组
选择新{的ParentId = grouped.Key,计数= grouped.Count(T =>!t.ChildId = NULL)}
 

Let's say I have this SQL:

SELECT p.ParentId, COUNT(c.ChildId)
FROM ParentTable p
  LEFT OUTER JOIN ChildTable c ON p.ParentId = c.ChildParentId
GROUP BY p.ParentId

How can I translate this into LINQ to SQL? I got stuck at the COUNT(c.ChildId), the generated SQL always seems to output COUNT(*). Here's what I got so far:

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() }

Thank you!

解决方案

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) }