2017-04-14 16 views
0

我正在使用LINQ to Entities從SQL中選擇數據。LINQ Store表達式中不支持的方法

這裏是我的發言

var employee = from p in _context.employee 
         select p; 

employee = employee.Where(p => 
Helper.RemoveSpecialCharacters(p.IdentificationNumber). 
Equals(Helper.RemoveSpecialCharacters(search.IdentificationNumber))); 

var Results = employee.ToList(); 

我使用RemoveSpecialCharacters方法,我寫信給兩側對比無特殊字符進行比較。

這裏我得到錯誤,Linq-> Entity不支持「RemoveSpecialCharacters」方法,它不是有效的存儲表達式。

我知道它不能被翻譯成SQL。但是,如何使用LINQ進行這種比較?

RemoveSpecialCharacters方法

public static string RemoveSpecialCharacters(string str) 
    { 
     char[] arr = str.Where(c => (char.IsLetterOrDigit(c))).ToArray(); 

     str = new string(arr); 

     return str; 
    } 

我怎樣才能把這個LINQ讓SQL理解,如果方法名被轉換爲LINQ店那麼也許。

+1

順便說一句,var employee = from _context.employee select p;'被翻譯成var employee =(_context.employee);'(C#語言規範版本5.0,7.16.2.5選擇子句) 。 – Philippe

+0

理想情況下,您應該能夠創建一個MethodCall表達式,爲您的IQueryable查詢工作,它只是無法翻譯方法,從'Expression Tree'編譯'Func'時 –

+0

使用'Regex.Replace'檢出代碼 –

回答

2

如果你可以表達你的SQL RemoveSpecialCharacters,你可以有一個計算IdentificationNumberWithoutSpecialCharacters柱呈現你的員工一個SQL視圖,然後在其上進行篩選。

您還可以通過爲SQL Server創建.NET程序集來重用該方法的C#實現。

+0

如何在Sql中表示'RemoveSpecialCharacters',你應該已經回答了這個部分,隨着數據大小的增加,Sql CLR或者動態Sql不是性能的好選擇。沒有代碼,這應該是比回答更多的評論 –

0

.ToList()完成了你最初的數據庫查詢,並給你一個 內存中表示繼續努力,修改你的對象。

var employee = from p in _context.employee 
         select p.ToList(); 
string searchIdent = Helper.RemoveSpecialCharacters(search.IdentificationNumber); 

employee = employee.Where(p => 
Helper.RemoveSpecialCharacters(p.IdentificationNumber). 
Equals(searchIdent)); 

var Results = employee; 
+4

這將在過濾之前將整個員工表拉入內存。 – Philippe

+0

是的,不是我想要做的事情。 –

+1

即使拉整個表是唯一的解決方案,我會用'.AsEnumerable()替換'.ToList()',以避免創建列表並在內存中保留被丟棄的對象。 – Philippe

0

使用Regex.Replace考慮,大多會被你所使用的Linq to Entities提供商轉化爲正確的表達,目前的代碼有問題,因爲可查詢的提供者不知道如何方法調用轉換爲查詢表達式,對LINQ

要求

正則表達式

Regex regex = new Regex("[^a-zA-Z0-9]");

修改代碼

var employee = from p in _context.employee select p; 

employee = employee.Where(p => 
regex.Replace(p.IdentificationNumber,""). 
Equals(regex.Replace(search.IdentificationNumber,""))); 

var Results = employee.ToList(); 
相關問題