簡體   English   中英

用干凈的EF Core查詢替換Entity Framework FromSql()

[英]Replace Entity Framework FromSql() with clean EF Core query

我想知道如何用干凈的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。 我試圖用SUMGROUPCONVERT()創建東西,但總是遇到一些麻煩。

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查詢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM