我有三个表一是" Allowance"," Balance"和" TimeoffRequests"在这三个表中的公共列是EmployeeId和TimeoffTypeId,现在我需要通过分组他们timeoffTypeId和EmployeeId表" 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"编辑器,我发现它正在应用Cross或Outer Join代替"左连接"将是什么原因.
如果我删除此行代码" where penReq.TimeOffTypeID
== UA.TimeOffTypeID"这显示所有timeoffTypes与cross join有类似repeatation

如何使用Grouped数据实现左连接,如果timeofftypes没有任何请求,则显示空值?
您可能希望将 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)
| 归档时间: |
|
| 查看次数: |
129 次 |
| 最近记录: |