score:13

Accepted answer

LINQ Expression translates into under laying data source language, in your case its SQL, and in LINQ to Entities DateTime.AddMinutes doesn't have any implementation which would translate the query to corresponding equivalent in SQL. That is why .Net framework provided.

System.Data.Objects.EntityFunctions.AddMinutes

You should see: Date and Time Canonical Functions

You can have your query as:

   var resultSet = ( from entity in _dbContext.EntityCollection
                     where /*non-date-related where clause stuff*/
                           && 
                           entity.DateAdded <= 
                          System.Data.Objects.EntityFunctions.AddMinutes(
                                 DateTime.Now, -1 * timeElapsedThresholdInMinutes)
                     select entity);

But in your case its better if you can calculate the value before hand, like in your second code sample, since that will avoid the conversion for every record.

score:0

I'd really like to understand why LINQ->Entities considers DateTime.Now.AddMinutes() as a .NET method that has no T-SQL equivalent

Because every mapping from .NET to T-SQL has to be manually implemented, and they just didn't implement this one...

score:5

EntityFunctions is obsolete (EF 6.x).

Please use DbFunctions class for DateTime manipulations.

e.g from cmd in context.Commands where cmd.ExecutedOn > DbFunctions.AddMilliseconds(baseDate, millisecondsToAdd) select cmd

score:1

I've been using the DbFunction for long time, until today I realized...why do I even need to bother with that DbFunction at all.

And here is what came to my mind:

var dateLimit = DateTime.Now.AddMinutes(-20);
var result = db.TableName.Where(x => x.MyDateTime > dateLimit);

I just took the 'AddMinutes' operation out of the linq expression.


Related Articles