dimanche 23 avril 2017

EF Core helper method for explicit loading references and collections

EF Core has support for explicit loading. The context has two overloads, one for references and one for collections.

Having two methods is not useful, and gets messy. I want a single method for accepting both as a params array.

So instead of this

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

I want to do this:

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

In my context class, I have this so far:

public async Task Load<TEntity, TProperty>(TEntity entity, params Expression<Func<TEntity, object>>[] propertyExpressions)
  where TEntity : class
  where TProperty : 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();
    }
  }
}

The problem line is shown above. The input is object but .Collection() expects IEnumerable<TProperty>.

How do I make this work?





Aucun commentaire:

Enregistrer un commentaire