我有一个员工表:
EmployeeID | EmployeeName
---------------------------
1 | Jack
2 | Jill
3 | Roger
还有一个 Occurrences 表:
OccurrenceID | EmployeeID | Points
--------------------------------------
1 | 1 | 5
2 | 2 | 3
3 | 1 | 1
我有一个有效的 LINQ 查询,它将两个表分组和汇总在一起:
groupedOccurrences = (from o in db.Occurrences.Include(o => o.Employee)
where o.OccurrenceDate >= beginDate
&& o.OccurrenceDate <= endDate
group o by o.Employee.EmployeeName into g
select new OccurrenceByQuarter
{
Name = g.Key,
Total = g.Sum(o => o.Points)
});
产生这个输出:
Jack 6
Jill 3
但我也想让员工 Roger 以 0 分出现在输出中。我尝试向 LINQ 查询添加连接,如下所示:
groupedOccurrences = (from e in db.Employees
from o in db.Occurrences
join o in db.Occurrences on e.EmployeeID equals o.EmployeeID into j1
from j2 in j1.DefaultIfEmpty()
group j2 by e.EmployeeName into g
select new OccurrenceByQuarter
{
Name = g.Key,
Total = g.Sum(o => o.Points)
});
但我最终得到的分数被大大夸大了(就像他们应该的 24 倍一样)。
我还尝试通过public int? Total { get; set; }
在我的 OccurrencesByQuarter 类中将 Total 的声明更改为 null 来让 Total 返回 0,但是当我尝试将 LINQ 查询更改为包含时,Total = g.Sum(o => o.Points) ?? 0
我收到一条错误消息,提示“操作员 ?? 无法应用到 int 和 int 类型的操作数”。
任何帮助将非常感激。