将SQL转换为Linqe

问题描述 投票:0回答:1

有人可以帮助将以下内容转换为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
c# asp.net-mvc linq-to-sql
1个回答
0
投票

由于连接和分组,您将需要构造的查询将变得相当复杂。由于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)
              };
© www.soinside.com 2019 - 2024. All rights reserved.