2014-01-07 147 views
5

如何在實體框架中使用替換方法。我使用下面的代碼,但遇到錯誤。LINQ to Entities不能識別Replace方法?

using (SepasProjectEntities sp=new SepasProjectEntities()) 
{ 
var query = (from p in sp.HISAccidentLocationMappings 
         where p.Name.Replace('y','x').Contains(txt1.Text) 
         select p 
          ).ToList(); 
} 

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 Replace(Char, Char)' method, and this method cannot be translated into a store expression.

+0

我應該爲'replace'方法做些什麼? –

+0

@RaymondMorphy檢查我的答案。 – Kehlan

回答

9

我通常使用LINQ查詢的其他格式,如:

using (SepasProjectEntities sp = new SepasProjectEntities()) 
{ 
    var query = sp.HISAccidentLocationmappings 
        .Where(p => p.Name != null 
         && p.Name 
          .Replace("y", "x") 
          .Contains(txt1.Text)) 
        .ToList(); 
} 

Replace(char, char)不會工作,但Replace(string, string)意志。 Contains(string)也應該有效。

+0

以這種方式,您將從數據庫加載所有HISAccidentLocationmappins對象,然後在服務器端對其進行過濾。例如,如果DB中的表有10000條記錄,WHERE將只過濾5條記錄,那麼所有的10000條記錄將被加載到應用程序,這是一個巨大的資源浪費。 –

+0

@SergeyLitvinov OP正試圖在LINQ查詢中使用'Replace()'和'Contains()'方法。我不認爲他有很多其他選擇。 – Kehlan

+0

我得到這個錯誤:'在App_Web_bmikir7o.dll中發生了類型'System.NullReferenceException'的異常,但沒有在用戶代碼中處理' –

11

基於this MSDN article包含由實體框架支持的方法列表 - 只有一個替換具有支持方法的重載,這是

System.String Replace(String oldValue, String newValue) 

而且不

System.String Replace(char oldValue, char newValue) 

,你是使用。嘗試從

Name.Replace('y','x') 

與字符串版本來替換它

Name.Replace("y","x") 

我沒有嘗試,但是從文檔基於它應該工作

+0

根據那篇文章 - Contains(string val)方法也受EF –

1

可以翻轉它周圍?因此,我問你是否可以對txt1.Text值進行替換(並將其存儲在本地變量中),然後將其與數據庫中的值進行比較(我相當確信String.Contains IS只要你使用單個參數重載)。

+0

支持我原本有這個想法,但後來才意識到'Contains()'實際上是由LINQ to Entities支持的。 – Kehlan

+0

錯誤是關於'替換'不'包含'。我認爲@SergeyLitvinov有最好的答案:支持'Replace'的某些重載,OP正在調用一個不是的。 –

+0

他的回答和我的經歷在編輯之後幾乎是一樣的:p – Kehlan

相關問題