如何使用按组数据创建左连接

V G*_*idu 5 c# linq left-join

我有三个表一是" Allowance"," Balance"和" TimeoffRequests"在这三个表中的公共列是EmployeeIdTimeoffTypeId,现在我需要通过分组他们timeoffTypeIdEmployeeId表" TimeoffRequests"得到一个请假的一个请求时间,并得到" TimeOffHours" .因为我写的代码就像

var query = (from tr in TimeOffRequests
             where tr.EmployeeID == 9
             group tr by new { tr.EmployeeID, tr.TimeOffTypeID } into res
             select new
             {
                 EmployeeID = res.Key.EmployeeID,
                 TimeOffTypeID = res.Key.TimeOffTypeID,
                 TotalHours = res.Sum(x => x.TimeOffHours)
             }).AsEnumerable();
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在我需要将这些结果与第一个表联系起来,并且必须从所有员工中获取,并timeoffTypes从分组表中的UserAllowance相应TimeoffHours表中获取.为了得到左连接查询我写如下.

var requestResult = (from UA in UserAllowances
                     join UB in UserBalances on UA.EmployeeID equals UB.EmployeeID
                     where UA.TimeOffTypeID == UB.TimeOffTypeID && UA.EmployeeID == 9
                      && UA.TimeOffType.IsDeductableType == true      // LeftJoin

                     join rest in query on UA.EmployeeID equals rest.EmployeeID into penidngRequst
                     from penReq in penidngRequst.DefaultIfEmpty()
                     where penReq.TimeOffTypeID == UA.TimeOffTypeID

                     select new EmployeeTimeOffBalanceModel
                     {
                         TimeOffTypeID = UA.TimeOffTypeID != null ? UA.TimeOffTypeID : 0,
                         YearlyAllowanceHrs = (UA.YearlyAllowanceHrs != null) ? UA.YearlyAllowanceHrs : 0,
                         BalanceHours = UB.BalanceHrs != null ? UB.BalanceHrs : 0,
                         PendingHours = (decimal)((penReq != null) ? (penReq.TotalHours) : 0),
                         EmployeeID = UA != null ? UA.EmployeeID : 0,


                     }).ToList().Distinct();
Run Code Online (Sandbox Code Playgroud)

timeOFfType即使我leftjoin使用"into"和DefaultIfEmpty()关键字为查询编写,它也仅包含分组数据.结果如下:

在此输入图像描述

并通过使用"linqPad"编辑器,我发现它正在应用CrossOuter Join代替"左连接"将是什么原因.

如果我删除此行代码" where penReq.TimeOffTypeID == UA.TimeOffTypeID"这显示所有timeoffTypescross join有类似repeatation

反复的时间

如何使用Grouped数据实现左连接,如果timeofftypes没有任何请求,则显示空值?

Mug*_*aUK 1

您可能希望将 where 子句移至 on equals 子句中,如下所示

join rest in query on new { UA.EmployeeID, UA.TimeOffTypeID } equals new { rest.EmployeeID, rest.TimeOffTypeID } into penidngRequst
from penReq in penidngRequst.DefaultIfEmpty()
Run Code Online (Sandbox Code Playgroud)