asp.net – Entity Framework and Linq – Comparing DateTime – Education Career Blog

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;

,

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;

,

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;

Leave a Comment