如何在EF Repository Pattern中为GetAllByExpression传入Include表达式参数
解决方法
你只需要把需要Include的导航属性表达式,放到对应类型的表达式数组里传入即可,修改你的调用代码如下:
public async Task<IEnumerable<PropertyChargesRate>> GetPropertyChargeRates(int buildingId) { try { var g = new GenericRepository<PropertyChargesRate>(context); var result = await g.GetAllByExpression<PropertyChargesRate>( x => x.BuildingId == buildingId, // 传入includes参数:导航属性表达式数组 new Expression<Func<PropertyChargesRate, object>>[] { x => x.PropertyChargeType }); return result; } catch (Exception ex) { return null; } }
如果需要同时加载多个导航属性,直接在数组里追加表达式即可,示例:
new Expression<Func<PropertyChargesRate, object>>[] { x => x.PropertyChargeType, x => x.Building // 第二个要加载的导航属性 }
可选优化建议
你的泛型仓储类已经声明了泛型参数<T>,方法GetAllByExpression不需要重复声明泛型参数<T>,修改后的方法定义更简洁,调用时也不需要再指定方法的泛型类型:
// 去掉方法级重复的泛型参数<T>和对应的where约束 public async Task<IEnumerable<T>> GetAllByExpression(Expression<Func<T, bool>> expression, Expression<Func<T, object>>[] includes) { if (expression != null) { IQueryable<T> query = context.Set<T>(); foreach(var include in includes) { query = query.Include(include); } var result = await query.Where(expression).ToListAsync(); return result; } else { throw new ArgumentNullException(nameof(expression), "Invalid expression."); } }
优化后调用代码可以简化为:
var result = await g.GetAllByExpression( x => x.BuildingId == buildingId, new Expression<Func<PropertyChargesRate, object>>[] { x => x.PropertyChargeType });
内容的提问来源于stack exchange,提问作者Ibanez1408
相关产品推荐
相关产品推荐

