이미 제안 된대로 동적 라이브러리를 확장하는 것은 확실히 옵션입니다. 대안은 동적 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;
}
}
아무것도하지만,'FirstOrDefault()가'당신'Address1' (또는) 속성에 액세스하려고 할 때 예외를 던질 것'null' 값을 반환 할 수 있습니다. – DavidG
사실, 문자열을 올바르게 구문 분석 할 수 없기 때문에 특정 문제는 해당 지점에 도달하기 전에 발생합니다. FirstOrDefault() 대신 First()를 사용하여이 문제를 해결하는 대답을 수락합니다. –
이것은 도움이 될 수 있습니다. http://stackoverflow.com/questions/4849973/use-of-single-in-dynamic-linq – DavidG