jim
jim

Reputation: 27426

Entity Framework and Linq - Comparing DateTime

I have this code

public List<CalendarData> GetCalendarData(DateTime day)
    {
        List<CalendarData> list = new List<CalendarData>();
        using (dataContext = new VTCEntities())
        {

            DateTime test = new DateTime(2010, 10, 20, 17, 45, 0);

            var data = from z in dataContext.ReservationsSet
                       where z.start_time.Value == test
                       select z;

            foreach (var r in data)

What I'd like to do is have this

var data = from z in dataContext.ReservationsSet
                   where z.start_time.Value == day
                   select z;

the problem I have is that z.start_time has the time part also. The DateTime day doesn't have the time part recorded. Is there a way to compare the the date part of without getting this error

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported. 

when I do this

var data = from z in dataContext.ReservationsSet
           where z.start_time.Value.Date == test
           select z;

Upvotes: 2

Views: 5504

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564831

You can't use .Date in Entity Framework. The easiest way I know to handle this is to make a minimum + maximum day:

DateTime test = new DateTime(2010, 10, 20, 17, 45, 0);
DateTime startDay = test.Date;
DateTime endDay = startDay.AddDays(1);

var data = from z in dataContext.ReservationsSet
                   where z.start_time.Value >= startDay && z.start_time.Value < endDay
                   select z;

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503290

One option is to compute two values, like this:

DateTime day = ...;
DateTime nextDay = day.AddDays(1);

var data = from z in dataContext.ReservationsSet
                   where z.start_time.Value >= day &&
                         z.start_time.Value < nextDay
                   select z;

Upvotes: 7

Related Questions