2013-07-15 38 views
9

我需要調用ToShortDateString在LINQ查詢起訴lambda表達式:如何在linq lambda表達式中使用ToShortDateString?

toRet.Notification = Repositories 
    .portalDb.portal_notifications.OrderByDescending(p =>  p.id) 
    .FirstOrDefault(p => p.date.ToShortDateString() == shortDateString); 

,但我得到的錯誤:

An exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll but was not handled in user code

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

我能做些什麼,考慮到我確實需要使用ToShortDateString()

謝謝。

+0

這個線程可能有幫助:http://stackoverflow.com/questions/5370402/entity-framework-4-linq-how-to-convert-from-日期時間到字符串的查詢 –

+0

此線程應該幫助: http://stackoverflow.com/questions/18233495/linq-to-entities-does-not-recognize-the-method-system-string- tostring-method –

回答

4

你不應該」當你使用的是日期/時間數據時 - 只要你強制字符串比較,你突然不得不處理如何字符串被格式化。

相反,應該是這樣的:

var endDate = targetDate.AddDays(1); 

toRet.Notification = Repositories 
.portalDb.portal_notifications.OrderByDescending(p =>  p.id) 
.FirstOrDefault(p => p.date >= targetDate && p.date < endDate); 

(假設targetDate是不管你曾是被用來在你的代碼產生shortDateString,並DateTime變量已經是一個DateTime沒有時間價值)

+1

非常感謝你,達米安,它像一個魅力:) –

+0

我一直在尋找解決這個問題以及。在數據庫中我可能有像2012-06-06 20:14:50.367的日期。在查找2012年6月6日發佈的記錄時,我必須將日期從2012.06.06轉換爲2012.06.05 23:59,或者進行類似的操作。我想通過刪除時間組件來避免它,但不是從搜索日期中刪除數據庫中的日期。迎接每個人。非常好的門戶網站,很多有用的信息。 – Mariusz

20

Linq to Entities無法將ToSortDateString方法轉換爲SQL代碼。你不能在服務器端調用它。無論是移動過濾客戶端(即從服務器傳輸的所有數據到客戶端),或考慮使用server-side functions採取日期日期部分(你應該通過DateTime對象,而不是shortDateString):

EntityFunctions.TruncateTime(p.date) == dateWithoutTime 
+0

感謝您的快速回復。在寫FirstOrDefault後(p =>(EntityFunctions.TuncateTime(p.date)== shortDateString)我收到錯誤在System.Data.Entity.dll中發生類型'System.Data.EntityCommandExecutionException'的異常,但未在用戶中處理代碼 附加信息:執行命令定義時發生錯誤,請參閱內部例外以瞭解詳細信息 如果存在該異常的處理程序,則可以安全地繼續該程序。 –

+0

@OctavianEpure正如我上面所述,而不是傳遞字符串'shortDateString'你應該通過'DateTime'對象 –

+7

使用EF6,我不得不使用'DbFunctions.TruncateTime()' – Bpainter

-1

試試這個吧,

你也可以用下面的代碼。

Activity = String.Format("{0} {1}", String.Format("{0:dd-MMM-yyyy}", s.SLIDESHEETDATE), String.Format("{0:HH:mm}", s.ENDDATETIME)) 
-3

ToShortDateString()方法通常只用於日期而忽略時間戳。

您將通過使用以下查詢得到完全今天的結果集。

Repositories.portalDb.portal_notifications.OrderByDescending(p =>  p.id) 
     .FirstOrDefault(p => p.date.Date == DateTime.Now.Date); 

使用的DateTimeDate財產結構你可以只獲取該日期的記錄。

注意:Linq to Objects。只有當你可以(或有選擇)繞過ToShortDateString()方法

+1

'p.date.Date'會拋出異常。您不能在LINQ to Entities查詢中執行此操作。 – IronMan84

+0

你誤會了我。 'date'在這裏是'DateTime'類型的屬性。你可以用'CreatedDate'改變它。首先看看這個問題,請... – rana

+0

據我所知,'date'是'DateTime'屬性。我說的是你不能在LINQ to Entities中使用'date.Date',因爲它不知道如何將它轉換爲SQL。 – IronMan84