我想知道如何用干净的Entity Framework Core任务替换我的EF FromSql()
扩展。
我的查询如下:
activities = await _context.SubActivities
.FromSql(SubActivityQueryLibrary.GetRouteCombustionForDevices(deviceIds, dateFrom))
.Select(dict => new { Key = dict.StartTime, Value = Convert.ToDouble(dict.ConsumptionFuel) })
.OrderBy(o => o.Key)
.ToDictionaryAsync(x => x.Key, x => x.Value);
和SQL查询:
SELECT
CONVERT(DATE, StartTime) AS [StartTime],
SUM(ConsumptionFuel) AS [ConsumptionFuel]
FROM
[Flota24].[dbo].[ACTIVITIES]
WHERE
DeviceId IN ({string.Join(",", deviceIds)})
AND StartTime >= '{startDate:yyyy-MM-dd}'
GROUP BY
CONVERT(DATE, StartTime)
只想将难以转换的维护SQL代码转换为EF Core。我尝试使用SUM
,GROUP
和CONVERT()
创建一些内容,但总是遇到一些麻烦。
答案 0 :(得分:1)
EF Core任务应替换为以下代码:
activities = await _context.SubActivities
.Where(d => deviceIds.Contains(d.DeviceId) && d.StartTime >= dateFrom)
.GroupBy(o => o.StartTime.Date)
.Select(dict => new { Key = dict.Key, Value = Convert.ToDouble(dict.Sum(x => x.ConsumptionFuel)) })
.OrderBy(o => o.Key)
.ToDictionaryAsync(x => x.Key, x => x.Value);
可以删除SQL查询。