Asp.net mvc asp.net mvc中查询字符串导致的动态linq查询#

Asp.net mvc asp.net mvc中查询字符串导致的动态linq查询#,asp.net-mvc,linq-to-sql,Asp.net Mvc,Linq To Sql,在我的控制器中,我必须根据用户传递的指定查询字符串测试条件。 以下是我目前正在测试的条件: 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 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


欢迎使用您的所有答案,谢谢。

这个问题很可能是使用谓词的最佳选择。在这方面,我使用了alhambra谓词生成器,效果非常好:

基本上,您需要预先创建“null”谓词,并根据搜索参数的存在向其添加条件,然后查询接受该谓词作为参数的单个方法

当然,这假设您的搜索“对象”被很好地指定并且是常数,而不考虑参数(即它是单个“表”或指定的linq联接集)


希望这能提供一些线索。

假设您使用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();
var query=context.CreateObjectSet();
如果(!string.IsNullOrEmpty(cat))
query=query.Where(i=>i.CategoryName==cat);
如果(!string.IsNullOrEmpty(brand))
query=query.Where(i=>i.BrandName==brand);
... 等
var result=query.ToList();

谢谢,吉姆。正如我在你的链接中看到的,我不知道如何调用该方法以在我的控制器中使用。你能给我解释一下吗?