我正在尝试创建通用包含,但出现此错误。怎么了?谢谢。
包含路径表达式必须引用导航属性 在类型上定义。使用虚线路径进行参考导航 属性和用于集合导航的Select运算符 属性。
_repository.FindWithIncludes(..., new List<...>
{
x => x.Property1,
x => x.Property2,
});
public ICollection<TEntity> FindWithIncludes(Expression<Func<TEntity, bool>> currentExpression, List<Expression<Func<TEntity, object>>> propertiesToInclude)
{
using (var customContext = new TContext())
{
return customContext.Set<TEntity>().Include(x => propertiesToInclude.Select(currentProperty => currentProperty)).Where(currentExpression).ToList();
}
}
答案 0 :(得分:3)
Include
不能以这种方式使用:
.Include(x => propertiesToInclude.Select(currentProperty => currentProperty)
您需要的是对列表的每个表达式调用Include
:
.Include(x => x.Property1)
.Include(x => x.Property2)
...
.Include(x => x.PropertyN)
可以通过以下代码实现:
var query = customContext.Set<TEntity>().AsQueryable();
foreach (var property in propertiesToInclude)
query = query.Include(property);
return query.Where(currentExpression).ToList();
或与使用Aggregate
方法相同:
return propertiesToInclude
.Aggregate(customContext.Set<TEntity>().AsQueryable(), (q, p) => q.Include(p))
.Where(currentExpression).ToList();