我听到有人说,日期时间比较不会因为时间部分而起作用,因为日期时间有时间部分。
在sql中,我总是这样比较datetime,它工作得很好
select * from employee
where convert(varchar,dob,112) > '20111201' // this yyyymmdd format.我如何在LINQ查询中模拟这一点?
发布于 2012-09-14 02:18:53
要记住的一件事是,对表示数据库列的structs的操作不会转换成DateTime。因此,您不能编写这样的查询:
from e in EfEmployeeContext
where e.DOB.Date > new DateTime(2011,12,01);..。因为e.DOB表示数据库中的道布列,而EF不知道如何转换Date子属性。
但是,根据您想要的日期,有一个简单的解决方法:
在EfEmployeeContext where e.DOB > new DateTime(2011,12,01);
from e in EfEmployeeContext where e.DOB >=新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-14 02:22:47
如果您使用的是.NET 4或更高版本,只需使用EntityFunctions.TruncateTime助手方法即可。这将为您将这种类型的datetime- to -date转换为SQL。
from e in EfEmployeeContext
where EntityFunctions.TruncateTime(e.DOB) > new DateTime(2011,12,01);https://stackoverflow.com/questions/12412231
复制相似问题