【发布时间】:2019-06-09 05:55:29
【问题描述】:
我有一个具有 TimeSpan 属性 (Start) 和 int (Duration in minutes) 属性的实体。
我想执行一个 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;
转换为(取自 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)
我从 EntityFramework Core 收到的警告是
Microsoft.EntityFrameworkCore.Query:Warning: The LINQ expression 'where (DateTime.Now.TimeOfDay 无法翻译,将在本地进行评估。
我想要的 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])
【问题讨论】:
-
与问题无关:您可以这样做
TimeSpan.FromMinutes(n.duration)- 对我来说似乎更具可读性。
标签: c# linq .net-core entity-framework-core