Skip to content

LINQ Query Workaround for Comparing Dates (EF, LINQ2SQL,CodeFirst)

Updated: at 02:12 PM

 

I seem to always get this error all the time (kind of like I never learn).

 

image

 

Or, for you search engines reading:

LINQ to Entities does not recognize the method 'System.DateTime Subtract(System.TimeSpan)' method, and this method cannot be translated into a store expression.

 

The solution is very straight forward.  Just pull out the Subtract and compare the dates directly like this:

 

DateTime compareDateTime = DateTime.UtcNow.Subtract(new TimeSpan(0, 0, 15, 0));

// now get failures with last run more than 15 minutes ago
var usersFailedLasttime =
db.PushChannels.Where(a => a.RequestPushNotification.HasValue && a.RequestPushNotification.Value &&
a.PushNotificationLastRunSuccess.HasValue &&
!a.PushNotificationLastRunSuccess.Value &&
a.PushNotificationFailedDateTime.HasValue &&
a.PushNotificationFailedDateTime.Value < compareDateTime);
 
 
That’s it!  Now, since I’ve blogged this, maybe next time I’ll remember (or the Microsoft team will fix it)
 

Check out the ORM (Object Relational Mapper) PRISMA. The database access method I use in all my projects