2017-08-17 62 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")。通過反射來構建字符串很容易。