2016-04-12 141 views
1

我在ASP MVC中創建了一個actionresult,它應該顯示與我的Linq查詢匹配的記錄。它正常工作,直到我說:like運算符給出零結果

records.State == '0' && 

這個查詢(以T-SQL)返回SQL Management Studio中正確的結果,但不能使用LINQ:

public ActionResult Index(string q) 
    { 
       viewModel.Records = from records in db.records 
            where records.State == '0' && 
            records.Title.Contains(q) 
            || records.Title.Contains(q) 
            ||records.Project.Contains(q) 
            || records.Owner.Contains(q) 
            || records.Number.Contains(q) 
            select events; 
    } 
+2

是什麼State'的'類型? – Shyju

+0

@Shyju這個類型是tinyint –

+1

@CitizenDB那麼你爲什麼要把它與'char'比較呢?試試'records.State == 0'。通過比較'0',你實際上將它與數字值48比較 – juharr

回答

5

要小心你的邏輯。如果你想要的是

records.State == '0' && [whatever previous logic you have] 

你應該把你以前所有的邏輯在括號:

viewModel.Records = from records in db.records 
        where records.State == '0' && 
        (records.Title.Contains(q) 
        || records.Project.Contains(q) 
        || records.Owner.Contains(q) 
        || records.Number.Contains(q)) 
        select events; 

另外請注意,您有重複的情況records.Title.Contains(q),我在我的解決方案將其刪除。

另外,如果您的records.State是數字類型(如int,不char/string),那麼你不應該使用單引號,而應直接使用數量:

viewModel.Records = from records in db.records 
        where records.State == 0 && 
        (records.Title.Contains(q) 
        || records.Project.Contains(q) 
        || records.Owner.Contains(q) 
        || records.Number.Contains(q)) 
        select events; 
2

請嘗試以下

public ActionResult Index(string q) 
{ 
      viewModel.Records = from records in db.records 
           where records.State == 0 && 
           (records.Title.Contains(q) 
           || records.Title.Contains(q) 
           ||records.Project.Contains(q) 
           || records.Owner.Contains(q) 
           || records.Number.Contains(q)) 
           select events; 
} 
2

你的代碼將工作如果State屬性的類型是char類型,因爲的10是一個char

如果State類型爲int/tinyint(字節),你應該這樣做

where records.State == 0 
&& records.Title.Contains(q) 
2

Contains()電話看起來是正確的(雖然你有Title.Contains()兩次),但你提到你的State財產是tinyint,所以你會希望它比較本身(而不是字符串,你以前是):

public ActionResult Index(string q) 
{ 
      viewModel.Records = from records in db.records 
           where records.State == 0 && (records.Title.Contains(q) 
           ||records.Project.Contains(q) 
           || records.Owner.Contains(q) 
           || records.Number.Contains(q)) 
           select events; 
}