如何在具有多个表的Linq查询中使用聚合运算符?

时间:2015-03-20 09:09:14

标签: c# linq entity

我想在T-SQL下面的Linq查询中实现代码,

select rg.Name, Sum(si.TotalPoint) / Count(si.TotalPoint) from ScoreItem si    
inner join Score s on s.Id = si.ScoreId
inner join ProjectResearchGroup prg on prg.Id = si.ProjectResearchGroupId
inner join RgClone rg on rg.Id = prg.RgCloneId
where rg.Name in (N'26 Gros Kurşun Kalem Stant Skor Kartı'
--,N'A5/A6 Ayaklı Defter Stant Skor Kartı'
--,N'A5/A6 Defter Stant Skor Kartı'
--,N'Adel Metal Stant Skor Kartı')
group by rg.Name
order by Name

然后我在Linq重写了它们,因为我必须在EF中使用它,

(from si in ScoreItem
       join s in Score on si.ScoreId equals s.Id
       join prg in ProjectResearchGroup on si.ProjectResearchGroupId equals prg.Id
       join rg in RgClone on prg.RgCloneId equals rg.Id 
       group rg by rg.Name into g 
   select new {Name = g.Key, SISScore = g.Sum(rg.TotalPoint) / g.Count(rg.TotalPoint) })

但我有一些问题,所以如果您有任何建议,请随意与我分享,

1 个答案:

答案 0 :(得分:0)

请阅读我对这个问题的评论。我认为你应该这样纠正你的查询:

select new {Name = g.Key, SISScore = g.Average(x=>x.TotalPoint) })

因为SUM(Field)/Count(Field)表示您希望获得平均值;)