LINQ to Entities does not support 'Date'. Initializers, entity members, and entity navigation properties are the only things that work.

c# entity-framework linq linq-to-entities

Question

I'm getting an error when I attempt to run the following code.

public List<Log> GetLoggingData(DateTime LogDate, string title)
{
     var context = new LoggingEntities();
     var query = from t in context.Logs

           where t.Title == title 
           && t.Timestamp == LogDate

           select t;
     return query.ToList();
}

The issue I'm having is "The member of the type 'Date' that was supplied is not supported by LINQ to Entities. The only allowed types are initializers, entity members, and entity navigation properties." I've made many tries to convert everything into a string and compare it simply to the date portion, but I can't seem to find the appropriate combination. I really appreciate any assistance.

1
48
5/27/2016 10:49:10 AM

Accepted Answer

It's not the best option, but it does the job. I now have to use.net 3.5 for a number of reasons, and changing the database would be challenging. Anyway, here is a practical solution:

            var query = from t in context.Logs
                      where t.Title == title 
                      && t.Timestamp.Day == LogDate.Day
                      && t.Timestamp.Month == LogDate.Month
                      && t.Timestamp.Year == LogDate.Year
                      select t;

It's not the most tasteful answer, but it works.

24
8/16/2011 8:05:37 PM

Popular Answer

You may use DbFunctions.TruncateTime(DateTime?) if you are using EF 6.0+:

var query =
    from t in context.Logs
    where t.Title == title 
    && DbFunctions.TruncateTime(t.Timestamp) == LogDate.Date
    select t;

Note: For earlier version of EF where DbFunctions isn't available, EntityFunctions.TruncateTime(DateTime?) can be used instead.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow