Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DateTime?.Value.TimeOfDay in LINQ Query

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.

like image 635
Umagon Avatar asked Apr 03 '12 19:04

Umagon


1 Answers

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.

like image 138
jason Avatar answered Oct 03 '22 18:10

jason