2016-03-27 35 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; 
    } 
}