ef core支持显式加载。上下文有两个过载,一个用于参考,一个用于集合。
使用两种方法没有用,并且会变得凌乱。我想要一种将同时接受为参数数组的方法。
所以而不是这个
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<TProperty>
。
我如何使此工作?
考虑到这两种方法都返回NavigationEntry
派生类,并且两者都使用Microsoft.EntityFrameworkCore.Internal.ExpressionExtensions.GetPropertyAccess
方法从传递的lambda表达式获取PropertyInfo.Name
,您可以使用相同的方法来检索名称并使用该名称Navigation
方法:
使用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();
}
}