如何在EF中执行日期部分比较

我听说人们说日期时间比较不起作用只是因为时间部分,因为datetime有时间部分。

在SQL中我总是像这样比较日期时间,它工作正常

select * from employee where convert(varchar,dob,112) > '20111201' // this yyyymmdd format. 

我怎么能在LINQ查询中模拟这个?

要记住的一件事是,表示数据库列的DateTime结构上的操作不会转换为SQL。 所以,你不能写一个像这样的查询:

 from e in EfEmployeeContext where e.DOB.Date > new DateTime(2011,12,01); 

…因为e.DOB表示数据库中的DOB列,EF不知道如何翻译Date子属性。

但是,根据您想要的日期,有一个简单的解决方法:

  • 如果您想包括12/01/2011以及在该日期之后出生的所有员工,那么只需查询:

     from e in EfEmployeeContext where e.DOB > new DateTime(2011,12,01); 
  • 如果您只想包括2011年12月1日之后出生的员工,请查询:

     from e in EfEmployeeContext where e.DOB >= new DateTime(2011,12,02); 

简而言之,可以根据需要设置标准,即您要比较的常量或文字DateTime。 您无法对where谓词中表示DB列的属性进行根本性修改。 这意味着您无法将一个DateTime列与另一个DateTime列的投影进行比较,例如:

  //get all employees that were hired in the first six months of the year from e in EfEmployeeContext where e.HireDate < new DateTime(e.HireDate.Year, 7, 1); 

如果您使用的是.NET 4或更高版本,请使用EntityFunctions.TruncateTime帮助程序方法。 这会将此类日期时间到今天的转换转换为SQL。

 from e in EfEmployeeContext where EntityFunctions.TruncateTime(e.DOB) > new DateTime(2011,12,01);