包含路径表达式必须引用定义的导航属性

时间:2018-12-20 17:25:59

标签: c# entity-framework entity-framework-6 .net-4.7.2

我正在尝试创建通用包含,但出现此错误。怎么了?谢谢。

  

包含路径表达式必须引用导航属性   在类型上定义。使用虚线路径进行参考导航   属性和用于集合导航的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();
        }
    }

1 个答案:

答案 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();