加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:11:44 所属栏目:百科 来源:网络整理
导读:我听说人们说日期时间比较不起作用只是因为时间因素,因为datetime有时间部分. 在SQL中我总是像这样比较日期时间,它工作正常 select * from employeewhere convert(varchar,dob,112) '20111201' // this yyyymmdd format. 我怎么能在LINQ查询中模拟这个? 解
我听说人们说日期时间比较不起作用只是因为时间因素,因为datetime有时间部分.

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

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

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

解决方法

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

>如果您只想包括2011年12月1日之后出生的员工,请查询:

from e in EfEmployeeContext
where e.DOB >= new DateTime(2011,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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读