IQueryable条件包含

时间:2019-02-27 16:36:04

标签: c# entity-framework linq iqueryable

我有一些课程:

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 => {来自Employee emp in   dept.Employee,其中([emp] .Position == Position.Manager)选择   [emp]}'无效。该表达式应表示属性访问:   't => t.MyProperty'。要定位在派生类型上声明的导航,   指定目标类型的显式输入的lambda参数,例如   “(派生d)=> d.MyProperty”。

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

1 个答案:

答案 0 :(得分:1)

由于您的ManagersWorkers属性是Department类的直接子代,因此您没有在Department类中引用Employee,因此您不能为此目的使用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,
             });

希望能解决您的问题。