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

The Include path expression must refer to a navigation property defined

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

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.

_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();
        }
    }

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