【发布时间】: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<TProperty>。
我该如何进行这项工作?
【问题讨论】:
-
您可以使用
Collection()的字符串重载并传递属性表达式的属性名称。 -
@CodeCaster 是的,我看到了重载......但如果可能的话,我想让它在没有魔法字符串的情况下工作。我一直在使用这种方法,直到我可以让它发挥作用。
标签: c# entity-framework reflection lambda entity-framework-core