2017-08-17 63 views
0

我正在尝试.Include()模型的属性通过反射,允许我自动包含任何模型类型的所有属性。通过反射包含属性

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

我得到的错误是

InvalidOperationException异常: 属性表达 '项=> __property_0.GetValue(项目,空)' 是无效的。 表达式应表示属性访问:'t => t.MyProperty'。

有没有什么办法可以在lambda中实际引用属性的访问器?

回答

1

异常说明它。

.Include()使用表达式树,而不是委托或任意值(您只返回属性的值,而不是属性本身)。

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

但是构建表达式树很复杂。

取而代之,使用.Include()的字符串覆盖更容易,即.Include("MyProperty.ChildProperty.GrandchildProperty")。通过反射来构建字符串很容易。