1

빈 검색 매개 변수를 단락Linq에 된 IQueryable 짧은 나는 다음과 같은 방법으로 일반적인 저장소가

IQueryable<T> GetAllByFilter(Expression<Func<T, bool>> expression); 

지금은 하나 개 이상의 매개 변수가되었을 수 있습니다 프런트 엔드를 통해 검색 기능을 제공하기 위해 노력하고있어 입력했거나 공백으로 남겨 두었습니다. 빈 매개 변수에 대한 식의 단락에 문제가 있습니다.

문제

이 저장소에 다음의 예를 호출하여 입증 할 수 있습니다 paramnullSystem.NullReferenceException 경우

public IEnumerable<Foo> Search(string param) 
{ 
    var filteredFoos = _fooRepository.GetAllByFilter(
      f => string.IsNullOrEmpty(param) || f.Something == param); 

    return filteredFoos.ToList(); // throws exception 
} 

ToList()으로 쿼리를 열거하면 발생합니다.

나는 이것을 이해하지 못하거나 그것을 고치는 법을 모른다. 그래서 어떤 조언도 감사 할 것이다. 감사.

업데이트 : 아래의 댓글에 대한 응답으로 null 체크를 추가했습니다. 내 실제 코드는 문제가 될 수있는 곳 난 아직도 보이지 않아요이 지금

var test1 = _repository.GetAllByFilter(
    r => r != null && 
     (string.IsNullOrEmpty(param) 
       || (r.Field != null && r.Field.IndexOf(param.Trim()) != -1))); 

var test2 = test1.ToList(); // exception here 

것 같습니다.

편집 : 응답은 일반 저장소 GetAllByFilter 코드를 언급합니다 :

public IQueryable<T> GetAllByFilter(Expression<Func<T, bool>> expression) 
{ 
    return _dataContext.GetTable<T>().Where(expression); 
} 

메모를 그 나는 같은 테이블에 간단한 GetAll 쿼리

public IQueryable<T> GetAll() 
{ 
    return _dataContext.GetTable<T>(); 
} 

을 실행하면, 더 null 레코드가 (예상대로) 반환됩니다.

+1

를? –

+0

나는 그렇게 믿지 않는다. null이 아닌 문자열이 param으로 전달되는 한 질의는 잘 실행된다. 어떻게 f가 null이 될지 모르겠다. – fearofawhackplanet

+2

@fearofawhackplanet -'f'가 널 (null) 일 수있는 유일한 방법은'_fooRepository'가 널 항목을 리턴 한 경우입니다. 그게 아니라고 확신합니까? – GenericTypeTea

답변

0

케이크.

public IEnumerable<Foo> Search(string param) 
    { 
     Expression<Func<Foo, bool>> shortCircuit = a => true; 
     Expression<Func<Foo, bool>> normal = a => a.Something == param; 

     var filteredFoos = _fooRepository.GetAllByFilter(
      string.IsNullOrEmpty(param) ? shortCircuit : normal); 

     return filteredFoos.ToList(); // no more exception. 
    } 

당신은 꼭 당신이 그 된 IQueryable 방법으로 무엇을 던져 그들을 이해하는 기대할 수 없다, 기억하십시오. shortCircuit 표현식을 정적으로 만들 수 있습니다.

+1

pretty wugly ... –

2

은 간단하게 : 사운드 권리가 나던 당신이 'F'파라미터가 null의 경우 행사가이 arent 있는지 확인하고, 'f.Something'는 예외를 throw

public IEnumerable<Foo> Search(string param) 
{ 
    if (string.IsNullOrEmpty(param)) 
    { 
     return this.fooRepository.GetAll().ToArray(); 
    } 

    return this.fooRepository.GetAllByFilter(o => o.Field.Contains(param.Trim())).ToArray(); 
} 
+0

질문을 만들 때 "GetAll()"메서드가 없었습니다. 그것이 당신이 응용 프로그램의 모든 부분을 수정할 수있는 한 사람의 프로젝트라고 가정하는 것은 순진하지 않습니다. –

관련 문제