如何将左外连接添加到分组和求和LINQ查询

Spl*_*dor 3 c# linq

我有一个Employees表:

EmployeeID  |  EmployeeName
---------------------------
1           |  Jack
2           |  Jill
3           |  Roger
Run Code Online (Sandbox Code Playgroud)

和一个出现表:

OccurrenceID  |  EmployeeID  |  Points
--------------------------------------
1             |  1           |  5
2             |  2           |  3
3             |  1           |  1
Run Code Online (Sandbox Code Playgroud)

我有一个有效的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)
                       });
Run Code Online (Sandbox Code Playgroud)

哪个产生这个输出:

 Jack 6
 Jill 3
Run Code Online (Sandbox Code Playgroud)

但我想也让员工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)
                      });
Run Code Online (Sandbox Code Playgroud)

但是我最终得到了大量夸大的分数(就像他们应该的那样24倍).

我还尝试通过public int? Total { get; set; }在我的OccurrencesByQuarter类中更改Total的声明来获取Total返回0(如果为null)但是当我尝试将LINQ查询更改为包含时Total = g.Sum(o => o.Points) ?? 0我得到一个错误,上面写着"operator ??"无法应用到int和int类型的操作数".

任何帮助将非常感激.

Ser*_*kiy 6

使用组加入:

groupedOccurrences = (from e in db.Employees
                      join o in db.Occurrences.Where(x => 
                                  x.OccurrenceDate >= beginDate &&
                                  x.OccurrenceDate <= endDate)
                           on e.EmployeeID equals o.EmployeeID into g
                      select new OccurrenceByQuarter
                      {
                          Name = e.EmployeeName,
                          Total = g.Sum(x => (int?)x.Points) ?? 0
                      });
Run Code Online (Sandbox Code Playgroud)

结果将是:

Jack  6
Jill  3
Roger 0
Run Code Online (Sandbox Code Playgroud)

为了返回0空组,将summa属性转换为nullable,然后应用null-coalescing运算符返回默认值:g.Sum(x => (int?)x.Points) ?? 0