【发布时间】: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