简体   繁体   中英

Include property via reflection

I am trying to .Include() properties of a model via reflection, allowing me to automatically include all properties of any model type.

public static IQueryable<TSource> IncludeAll
    <TSource>(this IQueryable<TSource> source)
    where TSource : class
{
    return typeof(TSource).GetProperties()
        .Where(property => property.GetGetMethod().IsVirtual)
        .Aggregate(
            source,
            (current, property) => current.Include(
                item => property.GetValue(item, null)));
}

The error I get is

InvalidOperationException: The property expression 'item => __property_0.GetValue(item, null)' is not valid. The expression should represent a property access: 't => t.MyProperty'.

Is there any way to actually reference the property by its accessor in the lambda?

Exception says it.

The .Include() uses expression trees, not delegates or arbitrary values (you are only returning the value of the property, not the property itself) .

public static IIncludableQueryable<TEntity, TProperty> Include<TEntity, TProperty>([NotNullAttribute] this IQueryable<TEntity> source, [NotNullAttribute] Expression<Func<TEntity, TProperty>> navigationPropertyPath) where TEntity : class;

But building an expression tree is complicated.

Instead it's easier to use the string override of .Include() , ie .Include("MyProperty.ChildProperty.GrandchildProperty") . And building the string is easy enough via reflection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM