2014-10-06 7 views
0

다소 강력하지만 System.Linq.Dynamic 라이브러리에는 특히 복잡한 쿼리를 수행 할 때 어떤 규칙을 따라야하는지에 대한 문서가 부족합니다.동적 Linq 표현식에서 Func 매개 변수와 함께 linq 확장을 사용하는 방법은 무엇입니까?

내가 작업하고있는 쿼리에는 FirstOrDefault 호출이 포함되어 있지만 제대로 작동하지 않는 것으로 보입니다.

"Locations.FirstOrDefault(x => x.IsPrimaryLocation).Address1 as Address" 

내가 동적 LINQ와 함께 작동이 FirstOrDefault 식을 작성할 수 있습니다

여기에 전체 (unworking) 표현입니까?

이 표현식을 작성하는 올바른 방법은 무엇입니까?

+0

아무것도하지만,'FirstOrDefault()가'당신'Address1' (또는) 속성에 액세스하려고 할 때 예외를 던질 것'null' 값을 반환 할 수 있습니다. – DavidG

+0

사실, 문자열을 올바르게 구문 분석 할 수 없기 때문에 특정 문제는 해당 지점에 도달하기 전에 발생합니다. FirstOrDefault() 대신 First()를 사용하여이 문제를 해결하는 대답을 수락합니다. –

+0

이것은 도움이 될 수 있습니다. http://stackoverflow.com/questions/4849973/use-of-single-in-dynamic-linq – DavidG

답변

1

이미 제안 된대로 동적 라이브러리를 확장하는 것은 확실히 옵션입니다. 대안은 동적 Linq에있는 Where 주어진 컨텍스트 또는 저장소 "위치"에 대한 동적 객체를 사용 된 IQueryable

public static class DynamicQueryable { 

    public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object[] values) { return (IQueryable<T>) Where((IQueryable) source, predicate, values); } 

    public static IQueryable Where(this IQueryable source, string predicate, params object[] values)  { 

를 반환합니다.
그런 다음 동적 문자열 조건자를 포함 할 수있는 위치를 사용하고 firstOrDefault를 따르십시오.

DynamicLocations.Where("IsPrimaryLocation",new string[]).FirstOrDefault().Address1 as Address; 

정보를 필요한 경우
(캐치 또는 테스트는 null로 간주되지 않음)

DynamicLocations.Where(x => x.IsPrimaryLocation).FirstOrDefault().Address1 as Address; 

또는 동적 : 당신은 당신이로 인스턴스화 일반적인 저장소 클래스의 메소드에 노출 될 수 있습니다 동적

 public virtual IQueryable<TPoco> DynamicWhere(string predicate, params object[] values) { 
     return AllQ().Where(predicate, values); 
    } 

동적 일반 리포지토리 Y 인스턴스화 샘플 동적 LINQ와 함께 할

public class RepositoryFactory<TPoco> where TPoco : BaseObject,new() { 

    public IRepositoryBase<TPoco> GetRepository(DbContext context) { 

     // get the Pocotype for generic repository instantiation 
     var pocoTypes = new[] {typeof (TPoco)}; // but supports <T,U> 
     Type repBaseType = typeof (RepositoryBase<>); 

     IRepositoryBase<TPoco> repository = InstantiateRepository(context, repBaseType, pocoTypes); 

     return repository; 
    } 


    private IRepositoryBase<TPoco> InstantiateRepository(DbContext context, Type repType, params Type[] args) { 

     Type repGenericType = repType.MakeGenericType(args); 
     object repInstance = Activator.CreateInstance(repGenericType, context); 
     return (IRepositoryBase<TPoco>)repInstance; 
    } 

}