Consider my Event
class, and that i store DateTime
's in the DB as UTC dates. I simply want to return a filtered range based on the current date in a particular time zone - easy right?
This works fine:
IQueryable<Event> test1 = this.GetSortedEvents().Where(e => e.FinishDateTime.Date >= DateTime.UtcNow.Date);
This also works fine:
IQueryable<Event> test2 = this.GetSortedEvents().Where(e => e.FinishDateTime.AddHours(3).Date >= DateTime.UtcNow.AddHours(3).Date);
.. and additionally meets my time zone requirements.
So here i am thinking i can move this specific conversion out to this extension method:
public static DateTime RiyadhTimeFromUtc(this DateTime utcTime) { return utcTime.AddHours(3); }
This does NOT work:
IQueryable<Event> test3 = this.GetSortedEvents().Where(e => e.FinishDateTime.RiyadhTimeFromUtc().Date >= DateTime.UtcNow.RiyadhTimeFromUtc().Date);
.. and i get this NotSupportedException: Method 'System.DateTime RiyadhTimeFromUtc(System.DateTime)' has no supported translation to SQL.
This is obviously rubbish as the compiler happily converted it to SQL when the identical code was NOT in the extension method.
I've run into the "has no supported translation to SQL" problem before with certain types and most recently DateTime's. But my tests above and this link prove that the AddHours method should be supported in the SQL translation.
If someone could tell me what i'm doing wrong here (or a different workaround approach to this problem) i'd be really grateful.