我有以下方法,我想传递一个包含数组,并有实体框架加载和表达式数组中传递的关联:
public static async Task<T> FindAsync<T>(this GSCMContext context, Expression<Func<T, bool>> match, , params Expression<Func<T, object>>[] includes) where T : BaseEntity
{
var set = context.Set<T>();
if(includes != null)
{
foreach (var include in includes)
{
set.Include(include);
}
}
return await set<T>().SingleOrDefaultAsync(match);
}
问题是关联的加载方式与我运行此代码的方式不同:
context.Entities.Include(a => a.association).Find(id)
我不知道为什么我的代码不起作用。
答案 0 :(得分:2)
因为您只是忽略了Include
方法的结果。您应该修改您的方法以匹配下面的方法:
public static async Task<T> FindAsync<T>(this GSCMContext context,
Expression<Func<T, bool>> match,
params Expression<Func<T, object>>[] includes)
where T : BaseEntity
{
IQuerable<T> query = context.Set<T>();
if(includes != null)
{
foreach (var include in includes)
{
// Include returns result
query = query.Include(include);
}
}
return await query.SingleOrDefaultAsync(match);
}