2012-02-10 33 views
3

在我的控制器中,我必須根據用戶傳遞的指定查詢字符串來測試條件。
這些是我目前正在測試的條件:動態linq查詢由於asp.net mvc中的查詢字符串c#

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 
} 

我知道這是很難做到這樣。我想要的是通過使用任何方法來獲得結果,我查詢模型中的數據與基於控制器中指定查詢字符串的條件相匹配。
我必須用Dynamic LinQ或其他任何東西來替代它嗎?我真的不知道關於Dynamic LinQ。

歡迎所有的答案,並表示感謝。

回答

2

這個問題很可能成爲使用謂詞的絕佳選擇。我用的阿罕布拉謂詞建設者有很大的影響在這方面:

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

基本上,你創建你的「空」謂語前面,並且基於搜索參數存在添加條件,它,然後你會查詢接受謂詞作爲參數的單個方法。

這當然假定你的搜索'對象'被很好地指定並且與參數無關(即它不是一個'表'或是一組指定的linq連接)。

希望這能給出一些線索。

+0

感謝吉姆。正如我在鏈接中看到的,我不知道如何在控制器中調用該方法。你可以給我解釋一下嗎? – titi 2012-02-13 02:56:23

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();