Sto avendo un'entità con una proprietà TimeSpan
( Start
) e una proprietà int
( Duration
in minuti ).
Voglio eseguire una query linq che recupera tutte le righe che si applicano alla seguente logica:
Start <= DateTime.Now <= Start + Duration
Il mio 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;
si traduce in (come preso da 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)
L'avvertimento che sto ricevendo da EntityFramework Core è
Microsoft.EntityFrameworkCore.Query: Avviso: l'espressione LINQ 'where (DateTime.Now.TimeOfDay <= [n] .Start.Add (new TimeSpan (0, [n] .Duration, 0)))'> non può essere tradotto e saranno valutati localmente.
La query SQL che voglio è questa
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])
Soluzione semplice: non eseguire il calcolo come parte della query LINQ. Eseguire prima l'intervallo di tempo, quindi eseguire 2 istanze di data / ora come parametri. Fatto.