【问题标题】:Filter child entity LINQ methods过滤子实体 LINQ 方法
【发布时间】:2015-04-20 09:52:02
【问题描述】:

考虑以下查询:

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

Employees 实体没有LatestInformation 实体的导航属性(所以我不能直接访问其他实体),但LatestInformation 确实有Employees 实体的导航属性。

如何过滤此查询的最新信息实体?

预期的查询应如下所示:

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

那么,问题是如何过滤LatestInformation 实体?

【问题讨论】:

    标签: c# silverlight-4.0 linq-to-entities ria


    【解决方案1】:

    如果没有从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);
    

    【讨论】:

    • 我知道,但查询的目的是从员工那里获取数据以及可能存在或不存在的其他数据。
    • 实际上,如果我使用这种方法,我应该以某种方式将查询作为 LEFT JOIN 来满足我的需求.. 对吗?
    • @Alex 你的意思是你还想要没有任何LastInformation 条目的Employee
    • 是的,这就是我需要的。
    • @Alex 我更新了我的答案。你应该对你的问题做同样的事情。
    【解决方案2】:

    导航属性是什么意思?

    如果它是一些唯一的 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      相关资源
      最近更新 更多