【问题标题】:The Include path expression must refer to a navigation property defined包含路径表达式必须引用定义的导航属性
【发布时间】:2019-05-21 06:08:16
【问题描述】:

我正在尝试创建一个通用包含,但我收到此错误。怎么了?谢谢。

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      相关资源
      最近更新 更多