Using DateTime?.Value.TimeOfDay in LINQ Query

Go To StackoverFlow.com

8

I'm trying to do a Query with LINQ on ASP.NET MVC 3.

I have a model, lets call it Event. This Event object has a Date property, of DateTime?. What I want is to fetch the Events that are between 2 TimeSpans.

Right now my code looks like the following:

TimeSpan From = new TimeSpan(8,0,0);
TimeSpan Until = new TimeSpan(22,0,0);

var events =
    from e in db.Events
    where e.Date.Value.TimeOfDay >= From,
          e.Date.Value.TimeOfDay <= Until
    select e;

An exception is thrown, telling me that "The specified type member 'TimeOfDay' is not supported in LINQ to Entities."

I don't get a way around this problem, and I have been all day trying. Please help me, I'm so frustrated. :(

EDIT:

I Forgot to write here the "TimeOfDay" after e.Date.Value. Anyway, I did in my code.

I can't use DateTime because I have to filter Events that occur between certain time of the day, despite the date of the event.

2012-04-03 19:52
by Umagon
Your sample code doesn't even use TimeOfDay - I assume in reality it does, instead of using Date (as per your code) - Jon Skeet 2012-04-03 20:02
Why are you using two TimeSpan objects instead of two DateTime objects to filter the events - Steven 2012-04-03 20:02


13

Use the Date and Time Canonical Functions for LINQ-to-Entities. Specifically, look at

CreateTime(hour, minute, second)

If you need help calling a canonical function, look at How To: Call Canonical Functions.

2012-04-03 20:07
by jason
This seems to be on the track, I didn't know about Cannonical Functions. Thanks! But, how can I convert the DateTime to Time using these - Umagon 2012-04-03 20:20
@Umagon: Use datetime.Hour, datetime.Minute and datetime.Second - jason 2012-04-03 20:23
Oh my god! This solved my problem! I think I love you, LOL. Thank you very much! : - Umagon 2012-04-03 20:28
@Umagon: I create feelings in others that they themselves don't understand - jason 2012-04-03 20:30