2012-02-10 17 views
3

私のコントローラでは、ユーザーが渡した指定のクエリ文字列に基づいて条件をテストする必要があります。asp.netのクエリ文字列による動的linqクエリ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

基本的に、あなたがアップフロントあなたの「NULL」述語を作成し、検索パラメータの存在に基づいて、それに条件を追加したいですその述部をパラメーターとして受け入れた単一のメソッドを照会します。

これはもちろん、あなたの検索 'オブジェクト'がパラメータに関係なく(つまり、単一の 'テーブル'または指定されたlinq結合のセットであること)、よく指定され、定数であると仮定します。

これはいくつかの手がかりを与えることを望みます。あなたはLINQのクエリと仮定すると、

+0

おかげでジム。あなたのリンクに見られるように、私は自分のコントローラーでこのメソッドを使用する方法を知ることができません。それについて少し説明していただけますか? – titi

2

は、私はこのようにそれを行うだろう:

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