EF Core LINQ MySQL 时间段相减:计算两个时间字段的差值
在 EF Core 中,可以使用 'DbFunctions.DiffSeconds' 方法来计算两个时间段的差值。假设有一个 'MyTable' 实体类,其中包含 'StartTime' 和 'EndTime' 两个时间字段,你可以使用以下代码来计算它们的差值:
using Microsoft.EntityFrameworkCore;
var diffInSeconds = dbContext.MyTable
.Where(x => x.StartTime != null && x.EndTime != null)
.Select(x => (int?)DbFunctions.DiffSeconds(x.EndTime, x.StartTime))
.FirstOrDefault();
上述代码会查询 'MyTable' 表,筛选出 'StartTime' 和 'EndTime' 字段都不为空的记录,并计算它们的时间差(单位为秒)。最后,通过 'FirstOrDefault' 方法获取第一条记录的时间差值。
注意:'DbFunctions.DiffSeconds' 方法返回的是一个可空的整数,因此需要使用 'int?' 类型进行接收。
如果你想计算其他时间单位的差值,可以使用 'DbFunctions.DiffMinutes'、'DbFunctions.DiffHours' 等方法,具体取决于你需要的时间单位。
原文地址: https://www.cveoy.top/t/topic/gB75 著作权归作者所有。请勿转载和采集!