日期:2014-05-20  浏览次数:20786 次

Linq实现关联表-并分组查询?
select tc.Id, tc.Name, count(ta.Id) as articleTotal 
from dbo.tb_category as tc 
left join dbo.tb_article as ta on tc.Id = ta.categoryId 
group by tc.Name,tc.Id

我有一条这样的sql语句 我想转换成linq查询语句
请问怎么实现?即 关联表 并分组查询 因为对Linq还不是很熟悉……

------解决方案--------------------

var query=from t in  db.tb_category
          join o in db.tb_articleon t.Id equals o.categoryId into temp
           from tt in temp.DefaultIfEmpty() 
           group tt by new { Name=tc.Name, Id=tc.Id } into g
           select new { g.Key.Id, g.Key.Name,g.Count()}; 


手写的
------解决方案--------------------
var query=from tc in dbo.tb_category
          join ta in dbo.tb_article on tc.Id equals ta.categoryId into leftGroup
          from ta in leftGroup.DefaultIfEmpty()
          group new {tc,ta} by new {tc.Name,tc.Id} into g
          select new {g.Key.Id,g.Key.Name,articleTotal =g.Count()};