具有多个条件的左外连接 - 空例外

时间:2015-03-17 14:54:08

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

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

获取数据的第一个查询工作正常,过去十二个月的简单查询也是如此。

但是,当我尝试离开外连接它们时,我得到一个空异常,即使我在select new中处理每个字段为null。

我看不出我错在哪里......

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();

1 个答案:

答案 0 :(得分:0)

关键字join(通常是内部联接)与扩展方法DefaultIfEmpty一起在LINQ中模拟外连接(并且LINQ到实体将在生成实际SQL时实现) 。 DefaultIfEmpty说 - 应该deptsWithAllMonths是一个空集 - 返回一个包含单个默认对象的集合而不是......从第一个查询返回的匿名类型的默认对象是{{1 }}:

null

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

  

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