2010-10-19 104 views
2

比較我有這樣的代碼實體框架和LINQ - 日期時間

public List<CalendarData> GetCalendarData(DateTime day) 
    { 
     List<CalendarData> list = new List<CalendarData>(); 
     using (dataContext = new VTCEntities()) 
     { 

      DateTime test = new DateTime(2010, 10, 20, 17, 45, 0); 

      var data = from z in dataContext.ReservationsSet 
         where z.start_time.Value == test 
         select z; 

      foreach (var r in data) 

我希望做的是有這個

var data = from z in dataContext.ReservationsSet 
        where z.start_time.Value == day 
        select z; 

我的問題是,z.start_time有時間部分也是。 DateTime日沒有記錄時間部分。有沒有辦法比較的日期部分沒有收到此錯誤

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported. 

當我做這個

var data = from z in dataContext.ReservationsSet 
      where z.start_time.Value.Date == test 
      select z; 

回答

7

一種選擇是計算兩個值,就像這樣:

DateTime day = ...; 
DateTime nextDay = day.AddDays(1); 

var data = from z in dataContext.ReservationsSet 
        where z.start_time.Value >= day && 
         z.start_time.Value < nextDay 
        select z; 
+0

喬恩,謝謝,如何翻轉簡單。我不知道爲什麼我比他們更難做事。你是男人。 – jim 2010-10-19 17:04:28

2

您不能在實體框架中使用.Date。我知道處理這個最簡單的方法是使最低+最高日:

DateTime test = new DateTime(2010, 10, 20, 17, 45, 0); 
DateTime startDay = test.Date; 
DateTime endDay = startDay.AddDays(1); 

var data = from z in dataContext.ReservationsSet 
        where z.start_time.Value >= startDay && z.start_time.Value < endDay 
        select z; 
+0

非常感謝您的幫助。 – jim 2010-10-19 23:25:13