假设我有这个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) }
考虑使用子查询:
from p in context.ParentTable let cCount = ( from c in context.ChildTable where p.ParentId == c.ChildParentId select c ).Count() select new { ParentId = p.Key, Count = cCount } ;
如果查询类型通过关联连接,则简化为:
from p in context.ParentTable let cCount = p.Children.Count() select new { ParentId = p.Key, Count = cCount } ;
最后答复:
你不应该需要的左连接在所有如果你正在做的是伯爵().请注意,join...into
实际上它被转换为GroupJoin
返回分组,new{parent,IEnumerable
因此您只需要调用Count()
该组:
from p in context.ParentTable join c in context.ChildTable on p.ParentId equals c.ChildParentId into g select new { ParentId = p.Id, Count = g.Count() }
在扩展方法语法join into
等效于GroupJoin
(而join
没有一个into
是Join
):
context.ParentTable .GroupJoin( inner: context.ChildTable outerKeySelector: parent => parent.ParentId, innerKeySelector: child => child.ParentId, resultSelector: (parent, children) => new { parent.Id, Count = children.Count() } );
(from p in context.ParentTable join c in context.ChildTable on p.ParentId equals c.ChildParentId into j1 from j2 in j1.DefaultIfEmpty() select new { ParentId = p.ParentId, ChildId = j2==null? 0 : 1 }) .GroupBy(o=>o.ParentId) .Select(o=>new { ParentId = o.key, Count = o.Sum(p=>p.ChildId) })
虽然LINQ语法背后的想法是模拟SQL语法,但您不应该总是考虑直接将SQL代码转换为LINQ.在这种特殊情况下,我们不需要进行分组,因为join into是一个组连接本身.
这是我的解决方案:
from p in context.ParentTable join c in context.ChildTable on p.ParentId equals c.ChildParentId into joined select new { ParentId = p.ParentId, Count = joined.Count() }
与此处的大多数投票解决方案不同,我们在Count中不需要j1,j2和null检查(t => t.ChildId!= null)