在我的 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/