1

I have made a SelectExcept using dynamic linq based on https://stackoverflow.com/a/27205784/7468628.

Code:

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>();
    }

This works great with fields but from the moment my object is an object from a table and is joined with another table I lose the joined value when using SelectExcept. How can I still keep this joined value?

Community
  • 1
  • 1
smitske
  • 21
  • 3

1 Answers1

1

Well I found the answer so if anyone was wondering how to fix it here it is:

 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>();
    }

You needed typeof(object) for selected types else it does not collect the fields of your own defined classes.

smitske
  • 21
  • 3