2016-10-11 40 views
1

我正在開發一個帶有Kendo UI的asp.net MVC系統。我必須從視圖中的過濾器按鈕向控制器發送「日期」並過濾LINQ。我用這個代碼:錯誤,同時將可空datetime轉換爲LINQ中的字符串asp.net MVC

public ActionResult Grid_ReadLogAdminList([DataSourceRequest] DataSourceRequest request, string filterDate) 
     { 
      DateTime _temp; 
      if (!DateTime.TryParse(filterDate, out _temp)) 
       _temp = DateTime.Now; 

      return Json(_context.Entities<LogAdmin>().NoTracking().OrderByDescending(l => l.TimeStamp) 
       .Where(f => f.TimeStamp.Value.ToString("dd.MM.yyyy") == _temp.ToString("dd.MM.yyyy")) 
       .Select(l => new LogAdminInfo 
       { 
        Id = l.Id, 
        Message = l.Message, 
        MessageTemplate = l.MessageTemplate, 
        Level = l.Level, 
        TimeStamp = l.TimeStamp, 
        Exception = l.Exception, 
        Properties = l.Properties, 
        LogEvent = l.LogEvent, 
       }) 
       .ToDataSourceResult(request)); 
     } 

但它給了我一個「.Where」的錯誤。你應該知道TimeStamp字段是「datetime?」可空日期時間。

我收到此錯誤:

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

我怎樣才能解決這個錯誤?

+0

你需要先檢查您的日期爲null或不。 –

+0

我試圖去做。 .fhere(f =>(f.TimeStamp!= null?f.TimeStamp.Value.ToString(「dd.MM.yyyy」):「」)== _temp.ToString(「dd.MM.yyyy」))。 ...不起作用 –

+2

由於無法將其轉換爲T-SQL,因此Linq to Entities無法識別它。看到這裏:http://stackoverflow.com/a/34061692/2946329 –

回答

1

錯誤是相當指示LINQ到實體不支持的ToString方法,您可以使用另一種方法應該比較你的日期。

基於您的代碼我假設你只在日期時間進行比較的日期部分感興趣,所以我建議你嘗試DbFunctions.TruncateTime Method

Where(f => DbFunctions.TruncateTime(f.TimeStamp) == DbFunctions.TruncateTime(_temp)) 
+0

謝謝你的作品 –

1

更換

.Where(f => f.TimeStamp.Value.ToString("dd.MM.yyyy") == _temp.ToString("dd.MM.yyyy")) 

.Where(f => DbFunctions.TruncateTime(f.TimeStamp) == _temp) 
0
var tempDate = _temp.ToString("dd.MM.yyyy")  
    Json(_context.Entities<LogAdmin>().NoTracking().OrderByDescending(l => l.TimeStamp)  
.Select(l => new LogAdminInfo 
        { 
         Id = l.Id, 
         Message = l.Message, 
         MessageTemplate = l.MessageTemplate, 
         Level = l.Level, 
         TimeStamp = l.TimeStamp.Value.ToString("dd.MM.yyyy"), 
         Exception = l.Exception, 
         Properties = l.Properties, 
         LogEvent = l.LogEvent, 
        }).Where(l => l.TimeStamp = tempDate).Select(l) 
        .ToDataSourceResult(request));