2010-09-08 83 views
1

Hi people
我想在關鍵字字段中搜索,例如集合中的搜索關鍵字。
例如我的關鍵是「翼」關鍵字是「翼禮服其他」與空間我應該寫什麼,而不是它?
錯誤:方法'布爾比較(System.String,System.String)'沒有支持到SQL的轉換。在linq語句中添加一個自定義函數

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (Request.QueryString.HasKeys()) 
    { 
     DbDataContext db = new DbDataContext(); 
     var Query = from n in db.Products 
        where Compare(n.Keywords, Request.QueryString["key"]) 
        select n; 
     DataList1.DataSource = Query; 
     DataList1.DataBind(); 
    } 
} 

bool Compare(string keywords,string key) 
{ 
    string[] items = keywords.Split(' '); 
    foreach (string item in items) 
     if (item.Equals(key)) return true; 
    return false; 
} 
+1

不,你不能這樣做,它也被問及一百萬次。 – leppie 2010-09-08 07:01:18

+0

而不是?你說過一些事情是真的或錯的,但這不是解決方案。 – kamiar3001 2010-09-08 07:19:50

回答

2

在這種情況下,您可以使用Contains來代替您自制的Compare,它檢查字符串是否在字符串中。這也工作了LINQ

例如:

var Query = from n in db.Products 
       where n.Keywords.Contains(Request.QueryString["key"]) 
       select n; 

包含數組的作品也是如此。

+0

這是真的你能給我舉個例子嗎? – kamiar3001 2010-09-08 07:21:34

5

類似闕/ ANS:Custom Method in LINQ to SQL query

入住此爲文章全文:What is and what isn't possible with linq

以下是不可能的

// function used in filter 
static bool MyFunc(Nwind.Product p) 
{ 
    return p.ProductName.StartsWith("B"); 
} 
// query that uses MyFunc 
var q = 
    from p in db.Products 
    where MyPriceFunc(p.UnitPrice) > 30m 
    select p 

它編譯沒有錯誤,但是當你執行它LINQ到SQL拋出一個異常說:「靜態方法System.Boolean MyTest(LINQTest.Nwind.Product)沒有支持轉換爲SQL」。

當您嘗試從q獲取結果(例如使用foreach語句)時,實際上會引發異常,因爲LINQ to SQL只在需要結果時纔會嘗試將表達式樹轉換爲T-SQL,並且查詢必須被執行。

要修復該示例,您可以簡單地將檢查產品名稱是否以「B」開頭的代碼複製到查詢的where子句中,並且它將正常工作。

+0

你說過什麼是真的或錯的,但這不是解決方案。我應該用什麼來代替它?代碼或示例 – kamiar3001 2010-09-08 07:21:09