C#: Why is one of my .Where() conditions missing in my SQL query? -
i have method following line of code being run. it's supposed messages have been created within past 24 hours , aren't created in future time (because shouldn't possible).
messages.addrange(_dbcontext.messages .where(message => message.creationtime >= datetime.utcnow.addhours(-24) && message.creationtime <= datetime.utcnow) .tolist());
when application runs , passes above line, sql query ran:
select [message].[id], [message].[creationtime], [message].[value] [messages] [message] where([message].[creationtime] <= getutcdate())
this retrieves messages, instead of created within last 24 hours.
i want know why part of where() being ignored or not being transformed sql query, , can make work.
(message => message.creationtime >= datetime.utcnow.addhours(-24)
this problem sql query translation in ef core versions prior 2.0 (unsupported datetime
methods addhours
, adddays
etc.) leads called client evaluation. query should produce correct results, inefficient because second part of where
filter evaluated in memory after retrieving records match other condition.
it has been improved in ef core 2.0 generated sql looks (as expected):
select [message].[id], [message].[creationtime], [message].[value] [messages] [message] ([message].[creationtime] >= dateadd(hour, -24e0, getutcdate())) , ([message].[creationtime] <= getutcdate())
so either upgrade ef core 2.0, or use usual ef workaround putting datetime.utcnow.addhours(-24)
variable outside query , use inside.
Comments
Post a Comment