2014-09-12 2 views
0

어떻게 쓸 수 및 라인 조합은/매개 변수 테이블에서 같은 필드에서 값이 다른 유형, EQ람다 식으로 인라인 조건부 결합/자체 조인을 배치하는 방법은 무엇입니까?

Etype 
------- 
class A 
class B 
class C 

내가 양식에서 사용자의 선택에 따라 쿼리를 추가하고 요구하는 경우 람다를 사용하여 문을 가입 좋은 지금까지

public ActionResult Home(string title, string EtypeA) 
{ 
     EtypeA = (Convert.ToBoolean(EtypeA)) ? "typeA" : null; 
     var results = db.EList.Where(p => (title ==null || p.Title.Contains(title)) && 
             (EtypeA ==null || p.EtypeA.Contains(EtypeA))) 
     ... 
} 

것있다 (MVC 4 QS/매개 변수로 예정)하지만, 사용자가 ETYPE A와 ETYPE B와 결과를보고 싶어 그래서 만약 양식이 ETYPE 여과에 대한 확인란을 가지고, 그는 선택할 수 있습니다 체크 박스와 매개 변수는 모두

로 올 것입니다.
public ActionResult Home(string title, string EtypeA, string EtypeB) 

이제 인라인 쿼리를 작성하여 두 가지 유형의 E (직원)를 모두 참여시킬 수 있습니다. EtypeA 및 EtypeB이 ETYPE 필드의 값을 의미 때문에 내가 그들을 좋아 찾으려고 노력하고 있어요 :

public ActionResult Home(string title, string EtypeA, string EtypeB) 
    { 
      EtypeA = (Convert.ToBoolean(EtypeA)) ? "typeA" : null; 
      EtypeB = (Convert.ToBoolean(EtypeB)) ? "typeB" : null; 

var results = db.PartnersList.Where(p => (title ==null || p.Title.Trim().ToLower().Contains(title.ToLower())) && 
              ((EtypeA == null || p.EType.Contains(EtypeA) || (EtypeB == null || p.EType.Contains(EtypeB)) 

감사를 사전에 시간을. 이 경우

+0

'EList' 항목이 어떻게 보이는지 분명하지 않습니다. LINQ 예제에서 암시하는 별도의 속성 ('EtypeA == "typeA"','EtypeB == "typeB"', ...)이 있습니까, 아니면 다른 값을 가질 수있는 단일 속성을 갖고 있습니까? – Groo

+0

@Groo : Etype이 A와 B 인 모든 레코드를 필터링 할 쿼리가 오는 경우 &&에 3 가지 유형의 값 (typeA, typeB 및 typeC)이있는 단일 필드 Etype이 있습니다. – Vishal

답변

0

는 LINQ - 투 - SQL (EF의) 그리고 당신은 다음 Where 방법은 동일한 SQL 초래한다 다수가 방출되는 체인하는 IQueryable이 다음 EType 항상 포함되어있는 경우,

// not sure what EList is though 
var items = db.EList.AsQueryable(); // or `IEnumerable<T>` ? 

if (title != null) 
    items = items.Where(i => i.Title.Contains(title)); 

var typesToFilter = new List<string>(); 
if (Convert.ToBoolean(EtypeA)) 
    typesToFilter.Add("typeA"); 

if (Convert.ToBoolean(EtypeB)) 
    typesToFilter.Add("typeB"); 

if (typesToFilter.Count > 0) 
    items = items.Where(i => typesToFilter.Any(i.EType.Contains)); 

// this is where the provider will actually traverse the 
// expression tree, convert it to SQL and execute it:  
var results = items.ToList(); 

또한 정확하게 값 "TYPEA", "b를 입력"또는 "typeC"중 하나는, 당신은 String.Contains를 사용할 필요가 없습니다, 오히려 List.Contains (보다 효율적인 SQL을 방출 할) : 또는

if (typesToFilter.Count > 0) 
    items = items.Where(i => typesToFilter.Contains(i.EType)); 

를, 차이없이

var results = db.EList.Where(p => 
    (title == null || p.Title.Contains(title)) && 
    (typesToFilter.Count == 0 || typesToFilter.Contains(p.EType))); 
+0

원래 질문을 편집했습니다. 지금 그것이 의미가 있는지보십시오. – Vishal

+0

@Vishal :이게 작동하지 않습니까? – Groo

+0

마지막 코드 블록이 작동했습니다 :) 감사합니다. Groo. – Vishal

관련 문제