2016-03-27 66 views
2
public JsonResult GetThis(string typ1) 
{  
    ThisContext tpc = new ThisContext(); 
    IQueryable<ThisDB> oDataQuery = tpc.ThisDBs; 
    if (typ1 != null) 
    { 
     oDataQuery = oDataQuery.Where(a => a.Type == typ1); 
     var result = oDataQuery.ToList(); 
     return Json(result, JsonRequestBehavior.AllowGet); 
    } 
    else return null; 
} 

這裏的想法是創建一個基本的get方法,用'good'類型來選擇每一行,它不過是一個web API方法。針對Web API的動態LINQ查詢

問題是,我不明白爲什麼我的代碼不工作,它實際上什麼都沒有返回(數據庫不是空的,如果我查詢它沒有參數,它工作順利)。

這一定是一個愚蠢的錯誤,但我看不到它。我知道有多種方法來做動態LINQ查詢,但我想先了解爲什麼這不起作用。

謝謝你的時間!

+0

什麼是ThisDB和ThisContext? – derloopkat

+0

我使用實體框架6,所以ThisContext是我的dbcontext,ThisDB是一個模型,ThisDBs是ThisDB的ICollection。 –

+0

你說如果你「沒有參數地查詢它,它運行的很順利。」你是說如果你跳過'oDataQuery = oDataQuery.Where(a => a.Type == type1);'你會得到表中所有記錄的列表? – Lex

回答

0

第一件事情,你應該定義數據庫上下文範圍,因爲它是一次性的。(雖然它不會影響結果集,但它是一個很好的做法)

using(ThisContext tpc = new ThisContext()) 
{ 
     //Your code goes here. 
} 

接下來的事情是,你應該使用

string.IsNullOrEmpty() 
//or 
string.IsNullOrWhiteSpaces() 

方法可用來檢查字符串是否爲空或它可能包含內容爲空白或空字符串。

public JsonResult GetThis(string typ1) 
{  
    using(ThisContext tpc = new ThisContext()) 
    { 
     IQueryable<ThisDB> oDataQuery = tpc.ThisDBs; 
     if (!string.IsNullOrWhiteSpace(typ1)) 
     { 
      oDataQuery = oDataQuery.Where(a => a.Type == typ1); 
      var result = oDataQuery.ToList(); 
      return Json(result, JsonRequestBehavior.AllowGet); 
     } 
     else return null; 
    } 
}