[英]How do I perform date-part comparison in EF
我听说人们说日期时间比较不起作用只是因为时间因素,因为datetime有时间部分。
在SQL中我总是像这样比较日期时间,它工作正常
select * from employee
where convert(varchar,dob,112) > '20111201' // this yyyymmdd format.
我怎么能在LINQ查询中模拟这个?
如果您使用的是.NET 4或更高版本,请使用EntityFunctions.TruncateTime
帮助程序方法。 这会将这种类型的datetime-to-date转换为SQL。
from e in EfEmployeeContext
where EntityFunctions.TruncateTime(e.DOB) > new DateTime(2011,12,01);
要记住的一件事是,表示数据库列的DateTime结构上的操作不会转换为SQL。 所以,你不能写一个像这样的查询:
from e in EfEmployeeContext
where e.DOB.Date > new DateTime(2011,12,01);
...因为e.DOB表示数据库中的DOB列,EF不知道如何翻译Date子属性。
但是,根据您想要的日期,有一个简单的解决方法:
如果您想要包括在12/01/2011拥有DOB的所有员工以及在该日期之后出生的那些员工,那么只需查询:
from e in EfEmployeeContext where e.DOB > new DateTime(2011,12,01);
如果您只想包括2011年1月12日之后出生的员工,请查询:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.