如何通过 LINQ 将 TimeSpan 计算转换为 SQL

Dim*_*ris 5 c# linq entity-framework-core .net-core

我有一个具有TimeSpan属性 ( Start) 和int(Duration分钟为单位) 属性的实体。

我想执行一个 linq 查询,它将获取适用于以下逻辑的所有行:

Start <= DateTime.Now <= Start + Duration

我的 LINQ

from n in _context.Notifications
where n.Start <= DateTime.Now.TimeOfDay && DateTime.Now.TimeOfDay <= n.Start.Add(new TimeSpan(0, n.Duration, 0))
select n;      
Run Code Online (Sandbox Code Playgroud)

转换为(取自 SQL Server Profiler)

SELECT [n].[Id], [n].[Active], [n].[Created], [n].[Day], [n].[Duration], [n].[Name], [n].[Start], [n].[Type]
FROM [Notifications] AS [n]
WHERE [n].[Start] <= CAST(GETDATE() AS time)
Run Code Online (Sandbox Code Playgroud)

我从 EntityFramework Core 收到的警告是

Microsoft.EntityFrameworkCore.Query:Warning: LINQ 表达式 'where (DateTime.Now.TimeOfDay <= [n].Start.Add(new TimeSpan(0, [n].Duration, 0)))' > 无法翻译并将在当地进行评估。

我想要的 SQL 查询是这样的

SELECT [n].[Id], [n].[Active], [n].[Created], [n].[Day], [n].[Duration], [n].[Name], [n].[Start], [n].[Type]
FROM [Notifications] AS [n]
WHERE CAST(GETDATE() AS TIME) BETWEEN [n].[Start] AND DATEADD(MINUTE, [n].[Duration], [n].[Start])
Run Code Online (Sandbox Code Playgroud)

小智 0

简单的解决方案:不要将计算作为 LINQ 查询的一部分来运行。首先执行时间跨度,然后运行 ​​2 个 datetiime 实例作为参数。完毕。

  • 我不明白。如何在没有“开始”和“持续时间”数据的情况下进行时间跨度计算? (4认同)