将 SQL 转换为 Linqe

Convert SQL to Linqe

有人可以帮忙将以下内容转换为 LINQ To SQL 查询吗?

select e.date,e.StudentId, sum(q.Value)[sumation]

from [dbo].[EvaluationResults] e,[dbo].[QuestionsDetails] q

where e.QuestionsDetailsId=q.Id and e.StudentId=9
group by e.StudentId , e.Date

由于加入和分组,您需要构建的查询将相当复杂。由于 linq 在这些情况下会变得非常愚蠢,我会尝试一下。

这并不能完美地解决您的问题 - 您需要在原始数据上下文中进行替换,并且可能需要根据您的数据类型重新处理查询的某些部分。

var results = // This section maps to the FROM part of SQL
              from result in _db.EvaluationResults
              join detail in _db.QuestionDetails
                on result.QuestionDetailsId equals detail.Id
              // This section maps to the WHERE part of SQL
              where result.StudentId == 9
              // Since variable scoping is difficult for grouping,
              // you need to specify an intermediate select object
              // before grouping. It needs to contain everything
              // that is included in grouping or selection.
              select new
              {
                  result.StudentId,
                  result.Date,
                  detail.Value
              } into intermediate
              // This section maps to the GROUP BY part of SQL
              group intermediate by new
              {
                  intermediate.StudentId,
                  intermediate.Date
              } into grouped
              // This section maps to the SELECT part of SQL
              select new
              {
                  grouped.Key.StudentId,
                  grouped.Key.Date,
                  Summation = grouped.Sum(a => a.Value)
              };