我使用基于https://stackoverflow.com/a/27205784/7468628的动态linq创建了一个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) };
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时失去了连接值。我怎样才能保持这种联合价值?
答案 0 :(得分:1)
嗯,我找到了答案,所以如果有人想知道如何修复它,那就是:
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(对象),否则它不会收集您自己定义的类的字段。