Programing

LINQ to SQL Where 절 선택적 기준

lottogame 2020. 11. 1. 17:15
반응형

LINQ to SQL Where 절 선택적 기준


LINQ to SQL 쿼리로 작업 중이며 데이터 결과를 필터링 할 4 개의 선택적 필드가있는 문제가 발생했습니다. 선택적으로 값을 입력할지 여부를 선택할 수 있습니다. 특히, 값을 가질 수 있거나 빈 문자열을 가질 수있는 몇 개의 텍스트 상자와 값을 선택했거나 선택하지 않았을 수있는 몇 개의 드롭 다운 목록 ...

예를 들면 :

    using (TagsModelDataContext db = new TagsModelDataContext())
     {
        var query = from tags in db.TagsHeaders
                    where tags.CST.Equals(this.SelectedCust.CustCode.ToUpper()) 
                    && Utility.GetDate(DateTime.Parse(this.txtOrderDateFrom.Text)) <= tags.ORDDTE
                    && Utility.GetDate(DateTime.Parse(this.txtOrderDateTo.Text)) >= tags.ORDDTE
                    select tags;
        this.Results = query.ToADOTable(rec => new object[] { query });
    }

이제 다음 필드 / 필터를 추가해야하지만 사용자가 제공 한 경우에만 해당됩니다.

  1. 제품 번호-TagsHeaders에 조인 할 수있는 다른 테이블에서 가져옵니다.
  2. PO 번호-TagsHeaders 테이블 내의 필드입니다.
  3. 주문 번호-PO 번호와 유사하며 열만 다릅니다.
  4. 제품 상태-사용자가 드롭 다운에서 이것을 선택한 경우 여기에서 선택한 값을 적용해야합니다.

이미 가지고있는 쿼리는 훌륭하게 작동하지만 함수를 완료하려면 where 절에이 4 개의 다른 항목을 추가 할 수 있어야합니다. 방법을 모르겠습니다!


원래 쿼리를 코딩 할 수 있습니다.

var query = from tags in db.TagsHeaders
                where tags.CST.Equals(this.SelectedCust.CustCode.ToUpper()) 
                && Utility.GetDate(DateTime.Parse(this.txtOrderDateFrom.Text)) <= tags.ORDDTE
                && Utility.GetDate(DateTime.Parse(this.txtOrderDateTo.Text)) >= tags.ORDDTE
                select tags;

그런 다음 조건에 따라 추가 where 제약 조건을 추가합니다.

if(condition)
    query = query.Where(i => i.PONumber == "ABC"); 

쿼리 구문으로 이것을 코딩하는 방법을 모르겠지만 id는 람다에서 작동합니다. 또한 초기 쿼리에 대한 쿼리 구문 및 보조 필터에 대한 람다와 함께 작동합니다.

조건부 where 문을 포함하기 위해 잠시 코딩 한 확장 메서드 (아래)를 포함 할 수도 있습니다. (쿼리 구문과 잘 작동하지 않음) :

        var query = db.TagsHeaders
            .Where(tags => tags.CST.Equals(this.SelectedCust.CustCode.ToUpper()))
            .Where(tags => Utility.GetDate(DateTime.Parse(this.txtOrderDateFrom.Text)) <= tags.ORDDTE)
            .Where(tags => Utility.GetDate(DateTime.Parse(this.txtOrderDateTo.Text)) >= tags.ORDDTE)
            .WhereIf(condition1, tags => tags.PONumber == "ABC")
            .WhereIf(condition2, tags => tags.XYZ > 123);

확장 방법 :

public static IQueryable<TSource> WhereIf<TSource>(
    this IQueryable<TSource> source, bool condition,
    Expression<Func<TSource, bool>> predicate)
{
    if (condition)
        return source.Where(predicate);
    else
        return source;
}

다음은 IEnumerables에 대한 동일한 확장 방법입니다.

public static IEnumerable<TSource> WhereIf<TSource>(
    this IEnumerable<TSource> source, bool condition,
    Func<TSource, bool> predicate)
{
    if (condition)
        return source.Where(predicate);
    else
        return source;
}

매개 변수의 존재에 대한 조건부 검사를 사용하면됩니다. 예를 들면 :

where (string.IsNullOrEmpty(ProductNumber) || ProductNumber == tags.productNumber)

That way if the product number isn't entered that expression will return true in all cases, but if it is entered it will only return true when matching.


You have the ability to OR with ||.

Check out this thread, as it might give you some nice pointers: C# LINQ equivalent of a somewhat complex SQL query

참고URL : https://stackoverflow.com/questions/632434/linq-to-sql-where-clause-optional-criteria

반응형