How do I perform Date Comparison in EF query?

Kam picture Kam · Jul 6, 2009 · Viewed 96.4k times · Source

Please help. I am trying to figure out how to use DATE or DATETIME for comparison in a linq query.

Example: If I wanted all Employee names for those who started before today, I would do something like this in SQL:

SELECT EmployeeNameColumn
FROM EmployeeTable
WHERE StartDateColumn.Date <= GETDATE() //Today

But what about linq?

DateTime startDT = //Today

var EmployeeName =  
from e in db.employee
where e.StartDateColumn <= startDT 

The above WHERE doesn't work:

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

Answer

Mandeep Janjua picture Mandeep Janjua · Mar 10, 2012

Use the class DbFunctions for trimming the time portion.

using System.Data.Entity;

var bla = (from log in context.Contacts
           where DbFunctions.TruncateTime(log.ModifiedDate) 
                              ==  DbFunctions.TruncateTime(today.Date)
           select log).FirstOrDefault();

Source: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/84d4e18b-7545-419b-9826-53ff1a0e2a62/