如何执行在EF日期部分比较 [英] How do I perform date-part comparison in EF

查看:355
本文介绍了如何执行在EF日期部分比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听到有人说日期时间比较不只是由于时间的一部分,因为日期时间有部分时间工作。

i heard people saying date time comparison do not work just due to time part because datetime has time part.

在SQL我一直比较日期时间这样的方式,它正常工作

in sql i always compare datetime like this way and it works fine

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



我怎么能在LINQ查询模拟此?

how could i simulate this in a LINQ query?

推荐答案

有一件事要记住的是,代表数据库中的列上的日期时间结构的操作不会转换为SQL。所以,你可以不写像查询:

The one thing to keep in mind is that operations on DateTime structs that represent database columns don't translate to SQL. So, you cannot write a query like:

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



...因为e.DOB表示在数据库中的出生日期栏,和EF将不知道。如何翻译日期子属性。

... because e.DOB represents the DOB column in the database, and EF won't know how to translate the Date sub-property.

然而,有这取决于你想要什么样的历史可以简单的解决方法:

However, there's an easy workaround depending on what dates you want:


  • 如果您要包括具有DOB上12/01/2011以及那些在该日期之后出生的所有员工,然后简单地查询:

  • If you want to include all employees that have a DOB on 12/01/2011 as well as those born after that date, then simply query:

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


  • 如果您希望只12/01/2011以后出生的员工,然后查询:

  • If you want to include only employees born after 12/01/2011, then query:

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


  • 在总之,标准,意思是一个常数或者你对文字比较日期时间,可以设置不过你想要的。你就不能做出激进的修改,以便代表那里谓词中DB列的属性。这意味着你不能在一个时间列比较另外一个DateTime列的投影,例如:

    In short, the criteria, meaning a constant or literal DateTime you're comparing against, can be set up however you want. You just can't make radical modifications to properties that represent DB columns within the where predicate. That means you can't compare one DateTime column to a projection of another DateTime column, for instance:

        //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);
    

    这篇关于如何执行在EF日期部分比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆