This works
DateTime dtYesterday = DateTime.Now.AddDays(-1);
data = data.Where(d => d.CreatedTime <= dtYesterday);
But this doesn’t
data = data.Where(d => d.CreatedTime <= DateTime.Now.AddDays(-1));
because EF cannot translate it into SQL. That’s fine.
But just out of curiosity, is there a way to force it to evaluate the value of DateTime.Now.AddDays(-1) before translating it to SQL?
I’m wondering if there is a syntax similar to this?
data = data.Where(d => d.CreatedTime <= ForceEvaluate(DateTime.Now.AddDays(-1)));
The difference between
IQueryable<T>andIEnumerable<T>is that the former preserves the expression the programmer (i.e. you) wrote to present it to the query engine that performs the query (i.e. the RDBMS). Figuring out thatDateTime.Now.AddDays(-1)is a function that needs to be evaluated would work, but that is too much magic compared to a simple and straightforward solution with familiar and easily recognizable syntax:Having to guess would rob programmers of the opportunity to pass functions such as
DateTime.Now.AddDays(-1)to the RDBMS: it is entirely conceivable that the current database date/time is different from your application server, potentially resulting in a different set of rows. On the other hand, introducing theForceEvaluatesyntax would be pointless, because if you must mark the expression to be evaluated, you might as well do it using the familiar way (see your code that I pasted above).