[英]Compare DateTimes in Entity Framework
我正在嘗試執行此操作,但是它不起作用,它返回空結果:
if (inputDate != null)
{
dataContext.myTable
.Where(r => r.myDate.HasValue &&
r.myDate.Value.Day == inputDate.Value.Day)
}
我想比較兩個可以為空的DateTime
值,我只想從數據庫中檢索屬於某個Date
DateTime
值。 為了簡化此問題,我首先嘗試僅比較其“ Day
值。
請不要將其標記為重復項,因為我正在使用EF5 ,所以我沒有DbFunctions.TruncateTime()
函數。
如您所說,實體框架將引發錯誤。 您最好的選擇是使用條件在一天的第一秒和一天的最后一秒之間的查詢。
if(inputDate != null)
{
/* Assuming inputDate.Value only contains the Date part.
i.e. : 2017-05-23 instead of 2017-05-23 10:00:32 */
DateTime inputDateFirstSecond = inputDate.Value;
DateTime inputDateLastSecond = inputDateFirstSecond
.AddHours(23)
.AddMinutes(59)
.AddSeconds(59);
dataContext.myTable.Where(r => r.myDate.HasValue &&
(r.myDate.Value >= inputDateFirstSecond && r.myDate.Value <= inputDateLastSecond)
)
}
有一些用於SQL Server的實體框架擴展,可讓您使用日期時間部分,但如果將來更改數據庫引擎,它們將無法使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.