【问题标题】:EF Core helper method for explicit loading references and collections用于显式加载引用和集合的 EF Core 帮助器方法
【发布时间】:2017-04-23 12:45:00
【问题描述】:

EF Core 支持explicit loading。上下文有两个重载,一个用于引用,一个用于集合。

有两种方法没有用,而且会变得混乱。我想要一种将两者都作为参数数组接受的方法。

所以不是这个

await context.Entry(customer).Collection(e => e.Orders).LoadAsync();
await context.Entry(customer).Collection(e => e.Returns).LoadAsync();
await context.Entry(customer).Reference(e => e.Account).LoadAsync();

我想这样做:

await context.Entry(customer).Load(e=>e.Orders, e=>e.Returns, e=>e.Account);

我认为这是可能的,因为context.Include(...) 有类似的东西,它接受集合和引用。

在我的上下文类中,到目前为止我有这个:

public async Task Load<TEntity>(TEntity entity, params Expression<Func<TEntity, object>>[] propertyExpressions)
  where TEntity : class
{

  foreach (var propertyExpression in propertyExpressions) {

    var isCollection = typeof(IEnumerable).GetTypeInfo()
                       .IsAssignableFrom(propertyExpression.Body.Type);

    if(isCollection)
    {
      await Entry(entity)
        .Collection(propertyExpression)     // problem is here !!!!!
        .LoadAsync();
    }
    else
    {
      await Entry(entity)
        .Reference(propertyExpression)
        .LoadAsync();
    }
  }
}

问题行如上所示。输入是object,但.Collection() 需要IEnumerable&lt;TProperty&gt;

我该如何进行这项工作?

【问题讨论】:

  • 您可以使用Collection() 的字符串重载并传递属性表达式的属性名称。
  • @CodeCaster 是的,我看到了重载......但如果可能的话,我想让它在没有魔法字符串的情况下工作。我一直在使用这种方法,直到我可以让它发挥作用。

标签: c# entity-framework reflection lambda entity-framework-core


【解决方案1】:

考虑到这两个方法都返回NavigationEntry派生类,并且都使用Microsoft.EntityFrameworkCore.Internal.ExpressionExtensions.GetPropertyAccess方法从传递的lambda表达式中获取PropertyInfo.Name,您可以使用相同的方法来检索名称,然后使用@ 987654322@方法:

使用 Microsoft.EntityFrameworkCore.Internal;

public async Task Load<TEntity>(TEntity entity, params Expression<Func<TEntity, object>>[] propertyExpressions)
    where TEntity : class
{
    foreach (var propertyExpression in propertyExpressions)
    {
        var propertyName = propertyExpression.GetPropertyAccess().Name;
        await Entry(entity).Navigation(propertyName).LoadAsync();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 2018-11-06
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    相关资源
    最近更新 更多