Wednesday, October 7, 2009

EF error: 'Date' is not supported in LINQ to Entities.

I got a strange error from EF today. The error was:

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

My query was something like this:


from log in context.LogEntries
where log.EndDate > DateTime.Now.Date
select log;


It took me a while to figure out what was going on. It was simply that I couldn't use the .Date property on DateTime in the query itself.

The fix was simple, use a local variable to store the Date value and then use that variable in the query:


DateTime today = DateTime.Now.Date;
from log in context.LogEntries
where log.EndDate > today
select log

If I had to guess what was going on, I would guess that EF must do some translation of DateTime.Now to the GetDate() method in T-SQL. So, when I tried DateTime.Now.Date, it wasn't able to do the translation to T-SQL. Instead when I used a variable it simply translated that to a T-SQL Server datetime value.