【问题标题】:Left Outer Join with Multiple Conditions - Null Exception具有多个条件的左外连接 - 空异常
【发布时间】:2015-05-20 01:47:24
【问题描述】:

我正在尝试创建一个按部门和月份显示效率的查询。即使没有该月的数据,我也需要每个月都包含在内。

获取数据的第一个查询与获取过去十二个月的简单查询一样工作正常。

但是,当我尝试将它们从外部加入时,我得到了一个空异常,即使我正在处理 select new 中的每个字段都为空。

我看不出哪里出错了……

var departmentMonthlyEfficiences =
    (from o in operations
     join contract in contracts on o.Contract equals contract.Sequence.ToString()
     group o by new { o.Department, o.LastWorkDate.Year, o.LastWorkDate.Month} into dm
     where dm.Sum(o => o.ActualHours) > 0
     select new { Department = dm.Key.Department, Year = dm.Key.Year, Month = dm.Key.Month, Efficiency = dm.Sum(o => o.PlannedHours) / dm.Sum(o => o.ActualHours) });

var now = DateTime.Now;
var months = Enumerable.Range(-12, 12)
    .Select(x => new { 
        Year = now.AddMonths(x).Year, 
        Month = now.AddMonths(x).Month });

var departmentAllMonthlyEfficiences = (
      from m in months
      join deptMonth in departmentMonthlyEfficiences on new { Month = m.Month, Year = m.Month } equals new { Month = deptMonth.Month, Year = deptMonth.Year } into deptsWithAllMonths
      from deptAllMonth in deptsWithAllMonths.DefaultIfEmpty()

      select new { 
        Department= deptAllMonth.Department == null ? "empty": deptAllMonth.Department, 
        Year=m.Year == null ? 2019: m.Year, 
        Month=m.Month == null ? 12:m.Month, 
        Efficiency=deptAllMonth.Efficiency == null ? 0: deptAllMonth.Efficiency  
      }).ToList();

【问题讨论】:

    标签: linq entity-framework linq-to-entities left-join


    【解决方案1】:

    关键字join(通常是内连接)和扩展方法DefaultIfEmpty 在LINQ 中模拟外连接(当生成实际SQL 时,LINQ-to-Entities 会这样做)。 DefaultIfEmpty 说 — 如果 deptsWithAllMonths 是一个空集 — 返回一个包含单个默认对象的集合...从第一个查询返回的匿名类型的默认对象是 null

    select new
    {
        Department = deptAllMonth == null || deptAllMonth.Department == null
                       ? "empty"
                       : deptAllMonth.Department,
        Year = m.Year,
        Month = m.Month,
        Efficiency = deptAllMonth == null || deptAllMonth.Efficiency == null
                       ? 0
                       : deptAllMonth.Efficiency
    }
    

    但是,您应该考虑以下建议:Navigation Properties are More Readable than Joins。使用导航属性的重要方面之一适用于您的问题:

    LINQ to SQL 和 LINQ to Entities 都合并空值。

    【讨论】:

      猜你喜欢
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多