筛选子实体 LINQ 方法

Filter child entity LINQ methods

考虑以下查询:

  IQueryable<Employee> ret = this.ObjectContext.Employees
            .Include("EmployeeInformation")
            .Include("LatestInformation")
            .Where(emp => emp.idJobTitle == 1 && emp.idCrtLoc == 1);

Employees 实体没有导航 属性 到 LatestInformation 的实体(所以我不能直接访问另一个实体)但是 LatestInformation 确实有一个导航 属性 到 Employees 实体。

如何过滤此查询的 LatestInformation 实体?

预期的查询应如下所示:

ret = ret.Where(r=> LatestInformation.Where(li => li.year == 2015)); // Ofcourse this piece of code is wrong.

所以,问题是如何过滤 LatestInformation 实体?

如果没有从EmployeeLatestInformation的导航属性,则反过来查询。类似于:

var ret = this.ObjectContext.LatestInfomration
    .Where(i => i.Employee != null && i.year == 2015)
    .Select(i => i.Employee)
    .Where(emp => emp.idJobTitle == 1 && emp.idCrtLoc == 1);

编辑以匹配下面的 OP 评论:

// Extract needed data:
var employeeIdListWithInfo = this.ObjectContext.LatestInfomration
    .Where(i => i.Employee != null)
    .Select(i => i.Employee.Id)
    .ToList();

// Build the query (not executed yet)
var employeeWithInformation = this.ObjectContext.LatestInfomration
    .Where(i => i.Employee != null && i.year == 2015)
    .Select(i => i.Employee)
    .Where(emp => emp.idJobTitle == 1 && emp.idCrtLoc == 1);

var lonelyEmployees = this.ObjectContext.Employee
    .Where(emp => !employeeIdListWithInfo.Contains(emp.Id));

var ret = employeeWithInformation.Union(lonelyEmployees);

导航是什么意思属性?

如果它是一些唯一的 id 那么你可以使用

List<int> latest = this.ObjectContext.LatestInformation.Select(lat=> lat.someid).ToList();

ret = ret.Where(r=> latest.Contains(ret.id)).Where(emp => emp.idJobTitle == 1 && emp.idCrtLoc == 1);