2012-04-13 104 views
0

我想在我的項目中進行搜索功能。MVC LINQ與哪裏條件

目前,我想將十進制值轉換爲與searchString進行比較的字符串。

當我把這樣的:

public ActionResult Search(string searchString) 
    { 

     var product = from a in _db.Product.Include(a => a.Category) 
         select a; 
     if (!String.IsNullOrEmpty(searchString)) 
     { 
      product = product.Where(a => a.model.ToUpper().Contains(searchString.ToUpper()) 
           || Convert.ToInt32(a.displaySize).ToString().Contains(searchString)); 
     } 
     return View(product.ToList()); 
    } 

它有錯誤,

'LINQ到實體無法識別方法 'System.String 的ToString()' 方法'。

如何比較十進制值和字符串值?

你能幫我嗎?

謝謝。

+0

重複的問題? http://stackoverflow.com/questions/10140634/mvc-where-condition-with-search-function – 2012-04-13 14:30:06

+0

我通過'SqlFunctions.StringConvert(a.displaySize).Contains(searchString)'解決了這個問題。 – wholee1 2012-04-13 14:54:58

回答

2

您不能使用無法轉換爲SQL的C#函數,如.ToString()。您可以前Where

product = product.ToList().Where(a => a.model.ToUpper().Contains(searchString.ToUpper()) 
            || Convert.ToInt32(a.displaySize).ToString().Contains(searchString)); 

編輯使用LINQ對象,而不是如果你的表是不是非常大,通過調用.ToList()

您可以使用函數從SqlFunctions命名空間。該功能可以輕鬆轉換爲SQL。

+0

在一個非常大的列表中,這將會非常緩慢,因爲ToList會導致linq被執行,然後你在哪裏執行。 – Qpirate 2012-04-13 14:32:06

+0

我已經提到調用.ToList()的方法只適用於有少量行的表。 – 2012-04-13 14:33:07

+0

對不起,我沒有看到那裏。但正如你所說的,我很抱歉 – Qpirate 2012-04-13 14:35:31

1

您可以嘗試將您的字符串值(查詢參數)轉換爲小數點並比較反轉。

1

看起來你正在尋找兩種不同的東西。我會在||上分割這個linq語句。如果您正在查找任何a.model,請轉到一種方法,如果您正在查找int值轉到另一個方法並將搜索字符串轉換爲linq statment之前的int值。這種方法想是這樣的:

int searchInt; 

if(int.TryParse(searchString, out searchInt)) 
{ 

    product = product.Where(a => a.displaySize == searchInt); 
} 

你必須這樣做,因爲SQL沒有一個ToString()方法...所以LINQ並不真正知道該怎麼做。請記住,這一切都轉換爲SQL。