EF Linq to Entities查询with groupby sum和min

时间:2011-01-13 22:48:11

标签: c# sql linq-to-sql entity-framework linq-to-entities

我正在努力让Linq to Entities Query正常工作,但我无法理解。

这是我的SQL查询,它运行正常:

SELECT SUM(ca.PointValue) as Points, ua.UserFBID, MIN(ua.[Date]) as FirstDate
  FROM [LeaderOfNow].[dbo].[QuestionAnswer] ca
  inner join [LeaderOfNow].[dbo].[LONUserAnswers] ua
  on ca.Id = ua.AnswerId
  group by ua.UserFBID
  order by Points desc, FirstDate asc

到目前为止,我最好的尝试是:

            var leaders = db.LONUserAnswers
                .GroupBy(a => a.UserFBID)
                .Select(a =>
                new 
                {
                    FBID = a.Key,
                    CurrentPoints = a.Select(v => v.QuestionAnswer.PointValue).Sum(),
                    FirstAnswered = a.Min(v => v.Date)
                })
.OrderByDescending(a => a.CurrentPoints)
                .OrderBy(a => a.FirstAnswered)
                .Take(10)
                .ToList();

然而,这会导致乱七八糟的sql并且只尊重第一个订单而不是第二个订单,我需要工作。关于我做错什么的任何建议?谢谢你的帮助。

1 个答案:

答案 0 :(得分:4)

当你链接OrderBy函数时,你必须使用ThenBy()ThenDescendingBy()作为后者。