开发者

Full outer join - Linq To SQL

I'm trying to use Linq to SQL to do a full outer join. I had this working for a basic example, but it didn't work when each side of the full outer join were generated from another inner join. Below's the code. I realise that this could probably be put into less queries - but I'd rather split them out to make them as readable as possible. Performance isn't an issue in this case.

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 fullOuterJo开发者_如何学JAVAinResults =  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 };

In my test, the ordersIn results is empty, and the ordersOut results has one row in it. So I want the final fullOuterJoinResults to have a row, but it's empty.


Literally a second after I post, I notice an error where I'm not using the productID results anywhere!!! :-/ I'll edit this post with my fix once I've got it working ...

[edit]

Okay, this seems to work:

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 };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜