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

时间:2014-01-31 15:51:22

标签: c# linq left-join

我有三个表一是“Allowance”,“Balance”和“TimeoffRequests”这三个表中的常见列是EmployeeIdTimeoffTypeId ,现在我需要通过将表格“timeoffTypeId”中的EmployeeIdTimeoffRequests分组来获取一个请假时间,并获得“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();

enter image description here

现在我需要将这些结果与第一个表联系起来,并且必须得到所有员工,timeoffTypesUserAllowance以及相应的 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();

只有 timeOFfType 包含分组数据,即使我使用“into”和leftjoin关键字为查询撰写了DefaultIfEmpty()。结果如下:

enter image description here

并且通过使用“linqPad”编辑器,我发现它正在应用CrossOuter Join而不是“左连接”,这将是原因。

如果我删除了这行代码 " where penReq.TimeOffTypeID == UA.TimeOffTypeID" ,则会显示timeoffTypes所有cross join并重复

with repeated timeoffhours

如果timeofftypes没有任何请求,我怎样才能与包含Grouped数据的表实现左连接并显示空值?

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

您可以更改

where penReq.TimeOffTypeID == UA.TimeOffTypeID

where penReq == null || penReq.TimeOffTypeID == UA.TimeOffTypeID