asp.net-mvc - 由于asp.net mvc c#中的查询字符串而动态linq查询

标签 asp.net-mvc linq-to-sql

在我的 Controller 中,我必须根据用户传递的指定查询字符串来测试条件。
这些是我当前正在测试的条件:

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   
}

我知道这样做很难。我想要的是通过使用任何方法来获取结果,该方法根据 Controller 中指定的查询字符串查询模型中符合条件的数据。
我是否必须将其替换为 Dynamic LinQ 或除此之外的其他内容?我真的不知道 Dynamic LinQ。

欢迎您的所有回答,谢谢。

最佳答案

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

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

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

这当然假设您的搜索“对象”是明确指定的并且无论参数如何都是恒定的(即它是单个“表”或一组指定的 linq 连接)。

希望这能提供一些线索。

关于asp.net-mvc - 由于asp.net mvc c#中的查询字符串而动态linq查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9226174/

相关文章:

jquery - ASP.NET MVC 中的链接样式失败问题

c# - 在 ASP.NET 动态数据中的单元格上插入自定义值

asp.net-mvc - 使用 Entity Framework 添加记录重复其他对象

asp.net-mvc - 直接在MVC中指定 View 位置是不是效率更高?

sql-server - SQL 到 Linq 表达式?

asp.net-mvc - LINQ to SQL分页和COUNT(*)

c# - 在某些情况下不会抛出 DuplicateKeyException

c# - 为什么 Func<> 和 Expression<Func<>> 可以互换?为什么一个对我有用?

c# - ASP.NET MVC 4 具有一个域模型用于多个应用程序和缓存

javascript - 为什么我无法从 javascript 访问我的模型对象