簡體   English   中英

如何在EF中執行日期部分比較

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM