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

时间:2012-09-13 18:07:14

标签: c# entity-framework tsql linq-to-entities datetime-comparison

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

在sql中我总是像这样比较日期时间并且它工作正常

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

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

2 个答案:

答案 0 :(得分:10)

如果您使用的是.NET 4或更高版本,请使用EntityFunctions.TruncateTime帮助程序方法。这会将这种类型的datetime-to-date转换为您的转换。

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

答案 1 :(得分:2)

要记住的一件事是,表示数据库列的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);