【问题标题】:IQueryable conditional includeIQueryable 条件包含
【发布时间】:2023-04-07 16:19:01
【问题描述】:

我有一些课程:

public Department {
  public HashSet<Employee> Managers {get; set;}
  public HashSet<Employee> Workers {get; set;}
  public HashSet<Asset> Assets {get; set;}
}

我正在使用 IQueryable 来获取部门集合:

IQueryable<Department> deparments = Context.Department.Where (
dept => dept.CompanyId = id)
.include (dept.Managers.Where (emp => emp.level == Position.Manager) as Managers)
.include (dept.Workers.Where (emp => emp.level == Position.Worker) as Workers)
.include (dept.Asset)

执行查询时出现错误。这样做的正确方法是什么?这是错误消息:

"Include 属性 lambda 表达式 'dept => {from Employee emp in dept.Employee where ([emp].Position == Position.Manager) 选择 [emp]}' 无效。该表达式应表示属性访问: 't => t.MyProperty'。要定位在派生类型上声明的导航, 指定目标类型的显式类型 lambda 参数,例如 '(Derived d) => d.MyProperty'.

有关包含相关数据的更多信息,请参阅http://go.microsoft.com/fwlink/?LinkID=746393。”

【问题讨论】:

  • 您能否提供错误信息?
  • 错误是必需的,所以我们有一个关于正在执行什么的指标。
  • 更新了错误信息。

标签: c# entity-framework linq iqueryable


【解决方案1】:

由于您的ManagersWorkers 属性是Department 类的直接子级,并且您没有在Employee 类中引用Department,因此您不能为此目的使用Include() .

我认为你应该使用子查询来做到这一点。

var query = (from d in Contex.Department
             where d.CompanyId == id
             select new Department{
                 Managers = d.Managers.where(m => m.level == Position.Manager),
                 Workers = d.Workers.where(w => w.level == Position.Worker),
                 Asset = d.Assets,
             });

希望它能解决您的问题。

【讨论】:

  • 包含不过滤任何数据。理想情况下,您的代码可以工作
猜你喜欢
  • 2018-10-17
  • 1970-01-01
  • 1970-01-01
  • 2017-04-20
  • 1970-01-01
  • 2011-04-24
  • 2016-11-02
  • 1970-01-01
  • 2019-10-21
相关资源
最近更新 更多