我听人说,日期时间比较不只是由于时间的一部分,因为日期时间有部分时间工作。
在SQL我一直比较喜欢的datetime这种方式,它工作正常
select * from employee
where convert(varchar,dob,112) > '20111201' // this yyyymmdd format.
我怎么能在LINQ查询模拟这个?
我听人说,日期时间比较不只是由于时间的一部分,因为日期时间有部分时间工作。
在SQL我一直比较喜欢的datetime这种方式,它工作正常
select * from employee
where convert(varchar,dob,112) > '20111201' // this yyyymmdd format.
我怎么能在LINQ查询模拟这个?
有一两件事要记住的是,代表数据库列于日期时间结构的操作不会转换为SQL。 所以,你不能写这样的查询:
from e in EfEmployeeContext
where e.DOB.Date > new DateTime(2011,12,01);
......因为e.DOB表示数据库中的DOB列,EF将不知道如何将日期子属性转换。
然而,有一个简单的解决方法取决于你想要什么日期:
如果你想包括对12/01/2011一个DOB以及那些在该日期之后出生的,然后简单地查询所有员工:
from e in EfEmployeeContext where e.DOB > new DateTime(2011,12,01);
如果你想只包括12/01/2011以后出生的员工,然后查询:
from e in EfEmployeeContext where e.DOB >= new DateTime(2011,12,02);
总之,标准,这意味着你要对比较恒定或文字日期时间,可以设置不过你想要的。 你不能让激进的修改,以便代表其中谓词中DB列的属性。 这意味着你不能在一个时间列的数据进行比较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);