2013-06-26 44 views
0

我第一次嘗試比較DateTime錯誤比較日期時間

var searchResult = new PagedData<SAMPLE_STOCK> 
{ 
Data = _db.SAMPLE_STOCK.Where(m => m.LAST_UPDATED.Date == lastUpdate.Date) 
}; 
return PartialView(searcReasult); 

它提供了以下錯誤

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

然後我寫下面的代碼

var searchResult = new PagedData<SAMPLE_STOCK> 
{ 
Data = _db.SAMPLE_STOCK.Where(m => m.LAST_UPDATED.Day == lastUpdate.Day 
           && m.LAST_UPDATED.Month == lastUpdate.Month 
           && m.LAST_UPDATED.Year==lastUpdate.Year) 
}; 

它工作正常。我的問題是......這些有什麼區別?

+0

閱讀此:http://stackoverflow.com/questions/16736252/using-datetime-in-linq-to-entities –

+1

可能的重複:http://stackoverflow.com/questions/7320608/simple-way-to -compare-日期功能於日期時間屬性-使用實體框架-4-及-1- – Abbas

回答

0

由於您的謂詞無法轉換爲SQL,因此引發異常。 如果你把它轉換爲可枚舉的,它可以工作,因爲你強制linq2object過濾使用,但我認爲你的第二個查詢比這更有效:

var searchResult = new PagedData<SAMPLE_STOCK> 
{ 
    Data = _db.SAMPLE_STOCK.AsEnumrable().Where(m => m.LAST_UPDATED.Date == lastUpdate.Date) 
}; 
return PartialView(searcReasult); 

這是你的選擇,這種選擇提供了更少的代碼,但更內存使用情況。

0

消息

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

是相當自我解釋。 SQL將不知道如何獲取DateTime類型的Date屬性。 它可以使用DateTime。它可以和Integers一起工作。 在你的情況下,你必須使它與整數一起工作。

就性能而言,我沒有看到任何不良影響。

PS:在SQL中支持Date數據類型與此無關。