[英]Linq comparing 2 dates
我只想比較日期。 表中的值為DateTime,格式為2014-01-29 09:00:00.000。 請指教謝謝
public static List<vwReportDate> GetDetail(string startDate, string endDate)
{
startDate = "2014-01-28";
endDate = "2014-01-28";
DateTime dtStart = Convert.ToDateTime(startDate);
DateTime dtEndDate = Convert.ToDateTime(endDate);
var entities = new DataEntiies();
var query = from c in entities.vwReportDate
where c.EventCreateDate >= dtStart && c.EventCreateDate <= dtEndDate
select c;
return query.ToList();
}
看來您正在使用Entity Framework和LINQ to EF。 如果是這樣,則不能使用DateTime.Date
屬性, 因為 LINQ to EF 不支持該屬性。 您必須改為使用EntityFunctions.TruncateTime(myDateTime)
靜態方法:
var query = from c in entities.vwReportDate
let eventDate = EntityFunctions.TruncateTime(c.EventCreateDate)
where eventDate >= dtStart && eventDate <= dtEndDate
select c;
我對這個不依賴於EF的問題的解決方法是在日期范圍的結尾使用“小於”(在將日期范圍的結尾提前一天之后):
startDate = "2014-01-28";
endDate = "2014-01-28";
DateTime dtStart = Convert.ToDateTime(startDate);
DateTime dtEndDate = Convert.ToDateTime(endDate).AddDays(1);
var entities = new DataEntiies();
var query = from c in entities.vwReportDate
where c.EventCreateDate >= dtStart && c.EventCreateDate < dtEndDate
select c;
return query.ToList();
問題:為什么您忽略方法調用者提供的參數值?
使用DateTime
結構的Date
屬性檢索“日期”部分。
獲取此實例的日期部分。
在代碼中使用它:
var query = from c in entities.vwReportDate
where c.EventCreateDate.Date >= dtStart && c.EventCreateDate.Date <= dtEndDate
select c;
如果您正在使用Entity Framework(看起來像您一樣),則必須使用EntityFunctions.TruncateTime
(幫助程序)方法,因為否則將無法轉換查詢。
var query = from c in entities.vwReportDate
where EntityFunctions.TruncateTime(c.EventCreateDate) >= dtStart && EntityFunctions.TruncateTime(c.EventCreateDate) <= dtEndDate
select c;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.