我正在尝试使用Linq to SQL来进行完全外连接。我有一个基本的例子,但是当完全外连接的每一边都是从另一个内连接生成时,它不起作用。下面是代码。我意识到这可能会被放入更少的查询 - 但我宁愿将它们分开以使它们尽可能可读。在这种情况下,性能不是问题。
var productIds = db.OrderItemsIncoming.Select(i => i.ProductID)
.Union(db.OrderItemsOutgoing.Select(o => o.ProductID))
.Distinct();
var ordersIn = from o in db.OrdersIncoming
join i in db.OrderItemsIncoming on o.OrderNumber equals i.OrderNumber
select new { o, i };
var ordersOut = from o in db.OrdersOutgoing
join i in db.OrderItemsOutgoing on o.OrderNumber equals i.OrderNumber
select new { o, i };
var fullOuterJoinResults = from i in ordersIn
join o in ordersOut on i.i.ProductID equals o.i.ProductID into t
from o in t.DefaultIfEmpty()
where i == null ^ o == null
select new { i, o };
在我的测试中,ordersIn结果为空,ordersOut结果中有一行。所以我希望最终的fullOuterJoinResults有一行,但它是空的。
答案 0 :(得分:1)
我发帖后的第二秒,我注意到一个错误,我没有在任何地方使用productID结果! : - /我将使用我的修复程序编辑这篇文章,一旦我完成它......
[编辑]
好的,这似乎有效:
var ordersIn = from o in db.OrdersIncoming
join i in db.OrderItemsIncoming on o.OrderNumber equals i.OrderNumber
select new { o, i };
var ordersOut = from o in db.OrdersOutgoing
join i in db.OrderItemsOutgoing on o.OrderNumber equals i.OrderNumber
select new { o, i };
var productIds = db.OrderItemsIncoming.Select(i => i.ProductID)
.Union(db.OrderItemsOutgoing.Select(o => o.ProductID))
.Distinct();
var fullOuterJoinResults = from pid in productIDs
join i in ordersIn on pid equals i.i.ProductID into t1
from i in t1.DefaultIfEmpty()
join o in ordersOut on pid equals o.i.ProductID into t2
from o in t2.DefaultIfEmpty()
where i == null ^ o == null
select new { i, o };