我有三个表一是“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();
现在我需要将这些结果与第一个表联系起来,并且必须得到所有员工,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();
只有 timeOFfType
包含分组数据,即使我使用“into”和leftjoin
关键字为查询撰写了DefaultIfEmpty()
。结果如下:
并且通过使用“linqPad”编辑器,我发现它正在应用Cross
或Outer Join
而不是“左连接”,这将是原因。
如果我删除了这行代码 " where penReq.TimeOffTypeID
== UA.TimeOffTypeID"
,则会显示timeoffTypes
所有cross join
并重复
如果timeofftypes
没有任何请求,我怎样才能与包含Grouped数据的表实现左连接并显示空值?
答案 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