2017-02-22 7 views
1

https://stackoverflow.com/a/27205784/7468628을 기반으로하는 동적 linq를 사용하여 SelectExcept를 만들었습니다.Select 조인 테이블 제거 제외

코드 :

public static IQueryable SelectExcept<TSource, TResult>(this IQueryable<TSource> source, List<string> excludeProperties) 
    { 

     var sourceType = typeof(TSource); 
     var allowedSelectTypes = new Type[] { typeof(string), typeof(ValueType) }; 
     var sourceProperties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => allowedSelectTypes.Any(t => t.IsAssignableFrom(((PropertyInfo)p).PropertyType))).Select(p => ((MemberInfo)p).Name); 
     var sourceFields = sourceType.GetFields(BindingFlags.Public | BindingFlags.Instance).Where(f => allowedSelectTypes.Any(t => t.IsAssignableFrom(((FieldInfo)f).FieldType))).Select(f => ((MemberInfo)f).Name); 

     var selectFields = sourceProperties.Concat(sourceFields).Where(p => !excludeProperties.Contains(p)).ToArray(); 

     var dynamicSelect = 
       string.Format("new({0})", 
         string.Join(", ", selectFields)); 

     return selectFields.Count() > 0 
      ? source.Select(dynamicSelect) 
      : Enumerable.Empty<TSource>().AsQueryable<TSource>(); 
    } 

이 필드를 잘 작동하지만 순간부터 내 객체가 객체가 테이블과 SelectExcept를 사용할 때이 결합 된 가치를 잃고 다른 테이블과 조인됩니다. 이 조인 된 값을 계속 유지하려면 어떻게해야합니까? 당신의 자신의 정의 된 클래스의 필드를 수집하지 않습니다 다른 선택 유형

public static IQueryable SelectExcept<TSource, TResult>(this IQueryable<TSource> source, List<string> excludeProperties) 
    { 

     var sourceType = typeof(TSource); 
     var allowedSelectTypes = new Type[] { typeof(string), typeof(ValueType), typeof(object) }; 
     var sourceProperties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => allowedSelectTypes.Any(t => t.IsAssignableFrom(((PropertyInfo)p).PropertyType))).Select(p => ((MemberInfo)p).Name); 
     var sourceFields = sourceType.GetFields(BindingFlags.Public | BindingFlags.Instance).Where(f => allowedSelectTypes.Any(t => t.IsAssignableFrom(((FieldInfo)f).FieldType))).Select(f => ((MemberInfo)f).Name); 
     var selectFields = sourceProperties.Concat(sourceFields).Where(p => !excludeProperties.Contains(p)).ToArray(); 

     var dynamicSelect = 
       string.Format("new({0})", 
         string.Join(", ", selectFields)); 

     return selectFields.Count() > 0 
      ? source.Select(dynamicSelect) 
      : Enumerable.Empty<TSource>().AsQueryable<TSource>(); 
    } 

당신은 대해서 typeof (개체) 필요 : 누군가가 여기에 그것을 해결하는 방법에 대해 궁금 해서요 그래서 만약

답변

1

잘 나는 답을 발견 .