7

我听到人们说日期时间比较仅由于时间部分而不起作用,因为日期时间有时间部分。

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

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

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

4

2 回答 2

10

如果您使用的是 .NET 4 或更高版本,只需使用EntityFunctions.TruncateTimehelper 方法。这将为您将这种类型的 datetime-to-date 转换转换为 SQL。

from e in EfEmployeeContext
where EntityFunctions.TruncateTime(e.DOB) > new DateTime(2011,12,01);
于 2012-09-13T18:22:47.010 回答
3

要记住的一件事是,对表示数据库列的 DateTime 结构的操作不会转换为 SQL。因此,您不能编写如下查询:

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

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

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

  • 如果您想包括在 2011 年 12 月 1 日拥有 DOB 的所有员工以及在该日期之后出生的员工,则只需查询:

    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);
于 2012-09-13T18:18:53.000 回答