Mig*_*ura 4 c# sql-server entity-framework-core
我需要取两个日期之差的平均值,四舍五入到小数点后两位。
使用实体框架核心,我使用了以下内容:
var average = await games
.Where(x => x.Finish.HasValue)
.AverageAsync(x => Math.Round((x.Finish.Value - x.Start).TotalDays, 2));
Run Code Online (Sandbox Code Playgroud)
这似乎正在内存中运行。
如何计算数据库(SQL)的平均值?
问题不是Average,而是时间跨度计算-当前EF Core(2.x)不支持时间跨度计算的通用SQL转换。
对于SqlServer,尽管可以使用EF Core 2.1中引入的某些DateDiff方法。它们都返回int值,因此您不能直接使用DateDiffDay来获取的等效值TimeSpan.TotalDays,但可以使用DateDiffHour / 24d或DateDiffMinute / (24d * 60)等进行模拟。
例如,
var average = await games
.Where(x => x.Finish.HasValue)
.AverageAsync(x => Math.Round(EF.Functions.DateDiffHour(x.Start, x.Finish.Value) / 24d, 2));
Run Code Online (Sandbox Code Playgroud)
转换为
var average = await games
.Where(x => x.Finish.HasValue)
.AverageAsync(x => Math.Round(EF.Functions.DateDiffHour(x.Start, x.Finish.Value) / 24d, 2));
Run Code Online (Sandbox Code Playgroud)