Search code examples
c#entity-frameworklinqlinq-to-entitiesdbfunctions

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


Using this code in Entity Framework I receive the following error. I need to get all the rows for a specific date, DateTimeStart is of type DataType in this format 2013-01-30 12:00:00.000

Code:

 var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
                    .Where(x =>  x.DateTimeStart.Date == currentDateTime.Date);

Error:

base {System.SystemException} = {"The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."}

Any ideas how to fix it?


Solution

  • DateTime.Date cannot be converted to SQL. Use EntityFunctions.TruncateTime method to get date part.

    var eventsCustom = eventCustomRepository
    .FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
    .Where(x => EntityFunctions.TruncateTime(x.DateTimeStart) == currentDate.Date);
    

    UPDATE: As @shankbond mentioned in comments, in Entity Framework 6 EntityFunctions is obsolete, and you should use DbFunctions class, which is shipped with Entity Framework.