2012-02-10 2 views
3

컨트롤러에서 사용자가 지정한 쿼리 문자열을 기반으로 조건을 테스트해야합니다.asp.net mvc 쿼리 문자열로 인해 동적 linq 쿼리가 발생했습니다. #

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

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