2011-09-21 77 views
1

有沒有機會在linq查詢中運行c#方法? 我需要做這樣的事情:在linq查詢中調用c#方法(實體框架)

//... 
class Match { 
    public double PrecentageMatching(string s1, string s2) { 
    //... 
    return result; // value from 0.0 to 1.0 
    } 
} 
//... 

string pattern = "nameOfRecord"; 
var similarRecords = db.Table.Select( 
    r => Match.PrecentageMatching(r.name, pattern) > 0.5 
); 

我知道有LINQ不會知道的方法PrecentageMatching。但我想知道是否有辦法做到這一點?

我正在使用實體框架。 我需要在數據庫端沒有存儲過程和彙編。我沒有訪問數據庫。

回答

5

首先,您需要從數據庫中提取數據,然後才進行轉換:

string pattern = "nameOfRecord"; 
var similarRecords = db.Table 
         .Select(r => r.name) 
         .ToList() // This call fetches the data from the DB 
         .Select(x => Match.PrecentageMatching(x, pattern) > 0.5); 

這不是在所有問題,因爲你只用你的方法轉化返回的數據。如果你想用你的方法過濾器使用Where返回的數據,你有一個問題,因爲你首先需要返回所有數據並過濾客戶端上的數據。如果桌子很大,這可能是個問題。

+0

它的。加工。謝謝。還有一件事...有沒有更改這個查詢的選項,我可以接收所有字段?因爲在你的查詢中,我只收到名稱字段。 – nosbor

+0

當然。刪除'.Select(r => r.name)'行並將最後一行改爲'.Select(x => Match.PrecentageMatching(x.name,pattern)> 0.5);'。 –

2

將您的PrecentageMatching方法更改爲靜態方法。然後它將能夠找到Match.PrecentageMatching方法。

此外,你在那裏做什麼將返回一個IEnumerable的布爾值。如果你想從表中返回記錄,你需要「Where」而不是「Select」。

編輯:根據評論,你需要調用ToList()方法。

+0

很好地捕捉到了「靜態」的缺失,但這不是問題。問題是EF數據提供者不知道如何將Match.PercentageMatching轉換爲SQL代碼,並且會拋出運行時異常。 –

+0

@DanielHilgarth不知道。 *不好意思*我只是使用基本的東西。投票你的答案。 –

+0

是的。丹尼爾是對的。這將編譯,但不會工作。您將得到一個異常:「LINQ to Entities不能識別方法'Int32 LevensteinDistance(System.String,System.String)'方法,並且此方法不能轉換爲存儲表達式。」 – nosbor