在Entity中使用SUM()转换SQL语句

时间:2015-02-03 14:54:43

标签: c# sql linq entity-framework

我尝试翻译此SQL代码:

SELECT w.Id, w.LastName, w.FirstName, SUM(d.Price*dt.Number) AS somme
FROM  Waiter w
INNER JOIN  Client c on w.Id = c.WaiterId
INNER JOIN  DisheOnTable dt on c.Id = dt.ClientId
INNER JOIN  Dishe d on dt.DisheId = d.Id
GROUP BY w.Id, w.LastName, w.FirstName
ORDER BY somme DESC;

在实体框架中。

我试过这样的事情

var query2 = (from w in db.Waiter
              join c in db.Client on w.Id equals c.WaiterId
              join dt in db.DisheOnTable on c.Id equals dt.ClientId
              join d in db.Dishe on dt.DisheId equals d.Id
              group w by new { w.Id, w.LastName, w.FirstName } into g
              //orderby g.Select() descending
              select new
              {
                  id = g.Key.Id,
                  lastname = g.Key.LastName,
                  firstname = g.Key.FirstName,
                  total = g.Sum(q => q.)
              });

但是我的总和不起作用(经过多次研究和尝试)并且我不知道如何乘以我的变量。

PS:SQL语句运行良好,我试过了。

谢谢你们的帮助! :)

1 个答案:

答案 0 :(得分:3)

您需要对dishDishOnTable别名进行分组,Price位于DishNumber位于DishOnTable

group new{ d,dt} by new {w.Id, w.LastName, w.FirstName} into g

现在总结你想要的列

 select new { 
             id = g.Key.Id, 
             lastname = g.Key.LastName, 
             firstname = g.Key.FirstName, 
             total = g.Sum(q => q.d.Price * q.dt.Number)
            }).OrderBy(x=>x.total)