在ASP.NET MVC C#中,由于查询字符串而产生动态Linq查询

4
在我的控制器中,我必须根据用户传递的指定查询字符串测试条件。这些是我目前正在测试的条件:
string dep = Request.QueryString["dep"];
string cat = Request.QueryString["cat"];
string brand = Request.QueryString["brand"];
string search = Request.QueryString["search"];

if(!string.IsNullOrEmpty(dep) && !string.IsNullOrEmpty(search))
//does the GetDepSearch() method    
}

if(!string.IsNullOrEmpty(dep) && !string.IsNullOrEmpty(brand)){
//does the GetDepBrand() method 
}

if(!string.IsNullOrEmpty(cat) && !string.IsNullOrEmpty(search)){
//does the GetCatSearch() method
}

if(!string.IsNullOrEmpty(cat) && !string.IsNullOrEmpty(brand)){
//does the GetCatBrand() method
}

if(!string.IsNullOrEmpty(dep) && !string.IsNullOrEmpty(cat) &&    
  !string.IsNullOrEmpty(search)){
//does the GetDepCatSearch() method
}

if(!string.IsNullOrEmpty(dep) && !string.IsNullOrEmpty(cat) && 
  !string.IsNullOrEmpty(brand)){
//does the GetDepCatBrand() method
}

if(!string.IsNullOrEmpty(dep) && !string.IsNullOrEmpty(cat) && 
   !string.IsNullOrEmpty(brand) && !string.IsNullOrEmpty(search)){
//does the GetDepCatBrandSearch() method
}

if(!string.IsNullOrEmpty(search) && !string.IsNullOrEmpty(brand)){
//does the GetSearchBrand() method
}

if(!string.IsNullOrEmpty(dep) && !string.IsNullOrEmpty(search) && 
  !string.IsNullOrEmpty(brand)){
//does the GetDepSearchBrand() method   
}

if(!string.IsNullOrEmpty(cat) && !string.IsNullOrEmpty(search) && 
  !string.IsNullOrEmpty(brand)){
//does the GetCatSearchBrand() method   
}

我知道这样做非常困难。我的目标是通过在控制器中使用任何方法查询数据模型中与指定查询字符串匹配的条件来获取结果。
我必须用动态LinQ或其他东西替换它吗? 我真的对动态LinQ一无所知。

欢迎您的回答,谢谢。

2个回答

2
假设您使用Linq进行查询,我会这样做:
var query = context.CreateObjectSet<MyEntity>();
if(!string.IsNullOrEmpty(cat))
    query = query.Where(i=>i.CategoryName == cat);

if(!string.IsNullOrEmpty(brand))
    query = query.Where(i=>i.BrandName == brand);

... etc

var result = query.ToList();

2
这个问题很适合使用谓词。我已经成功地使用了 Alhambra 谓词构建器来解决这个问题。

http://www.albahari.com/nutshell/predicatebuilder.aspx

基本上,您需要预先创建“null”谓词,并根据搜索参数的存在添加条件,然后查询一个接受该谓词作为参数的单个方法。
当然,这假设您的搜索“对象”已经被明确定义并且不受参数的影响(即它是单个“表”或指定的一组linq连接)。
希望这提供了一些线索。

谢谢Jim。根据你提供的链接,我不知道如何在我的控制器中调用那个方法。你能否给我解释一下? - titi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接