我目前在尝试将以下sql映射到EF lambda样式查询时失败了:
SQL:
SELECT ResellerId, Name, Month, SUM(MonthTotal) AS MonthTotal
FROM dbo.View_ResellerYearMonthBase
WHERE (Year = 2015) AND (EventId > 0) AND (ValidationResponse IS NOT NULL)
GROUP BY ResellerId, Month, Name
我已经尝试了
public JsonResult GetResellerAnnualReportData(int year, bool includeUnValidated, bool includeUnbooked)
{
var qry = _reportsDal.View_ResellerYearMonthBase.AsQueryable();
qry = qry.Where(x => x.Year == year);
if (!includeUnValidated) { qry = qry.Where(x => x.ValidationResponse.Length > 0); }
if (!includeUnbooked) { qry = qry.Where(x => x.EventId > 0); }
qry = qry.GroupBy(x => new { x.ResellerId, x.Month, x.Name }).Select(y => new ResellerAnnualReportDto
{
ResellerId = y.Key.ResellerId,
Month = y.Key.Month.Value,
Name = y.Key.Name,
SumMonthTotal = y.Sum(z => z.MonthTotal.Value)
});
throw new NotImplementedException();//keep the compiler happy for now
}
我应该如何使用函数参数(year,includeUnValidated等)来实现SQL查询
答案 0 :(得分:1)
.GroupBy(key => new { key.ResellerId, key.Month, key.Name},
el => el.MonthTotal,
(key, el) => new ResellerAnnualReportDto
{
ResellerId = key.ResellerId,
Month = key.Month,
Name = key.Name,
MonthTotal = el.Sum(s => s.MonthTotal)
}).ToList();
这使用the overload和keyselector,elementselector和resultselector。这样您就可以避免使用IGrouping<key,value>
并立即获得所需的结果。无法测试。
答案 1 :(得分:0)
以下是如何执行此操作:
var result = qry.GroupBy(x => new { x.ResellerId, x.Month, x.Name }).
Select(y => new {
y.Key.ResellerId,
y.Key.Month,
y.Key.Name,
SumMonthTotal = y.Sum(z => z.MonthTotal)
}).ToList();