我有两个具有1对多关系的表:WorkOrder
1 - * Service
他们通过字段建立关系:ServiceID
由于某些遗留原因,有些WorkOrder
没有Service
,但其ServiceID
字段保存为0
现在我要选择所有WorkOrders
iff
匹配Service
或WorkOrder
' s ServiceID
= 0
如果没有ServiceID = 0
要求,它应该是正常的左连接:
var result = from wo in WorkOrderQuery
join j in JobQuery on ... // join some other tables
join s in ServiceQuery on wo.ServiceID equals s.ServiceID into gg
from g in gg.DefaultIfEmpty()
select new
{
ServiceCode = g == null? "" : g.Code,
WorkOrderID = wo.WorkOrderID,
};
但我不知道何时添加此要求。任何建议都表示赞赏。
答案 0 :(得分:1)
不完全确定我已经理解但是试试这个:
var result = (from wo in WorkOrderQuery
join s in ServiceQuery on wo.ServiceID equals s.ServiceID into g
from s in g.DefaultIfEmpty()
where wo.ServiceID == 0 || s != null
select new
{
ServiceCode = s?.Code ?? string.Empty,
WorkOrderID = wo.WorkOrderID
}).ToList();
测试了这些数据:
List<dynamic> WorkOrderQuery = new List<dynamic>
{
new { WorkOrderID = 1, ServiceID = 1 },
new { WorkOrderID = 2, ServiceID = 2 },
new { WorkOrderID = 3, ServiceID = 0 }
};
List<dynamic> ServiceQuery = new List<dynamic>
{
new { ServiceID = 1, Code = "a" }
};
获得WorkOrderID
1,3
答案 1 :(得分:0)
如果没有ServiceID = 0要求,它应该是正常的左连接
根据定义left outer join
从左侧包含每条记录,无论是否存在匹配的右侧记录。
由于您的WorkOrder
位于联接的左侧,因此您应该使用正常的左连接,无论您的新要求是什么&#34;。