linq-to-sql实现left join,group by,count

linq-to-sql实现left join,group by,count

用linq-to-sql实现下面的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语句如下:

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) }
posted @ 2015-10-30 13:45  CreativeSpirit  阅读(1704)  评论(1编辑  收藏  举报