views:

179

answers:

1

Basically I want to be able to recreate this query in Linq

SELECT * 
FROM Customers

LEFT JOIN Orders LastOrder
ON LastOrder.CustomerId = Customers.CustomerId
&& LastOrder.CreatedOn = (Select MAX(CreatedOn) FROM Orders WHERE CustomerId = Customers.CustomerId)

LEFT JOIN OrderStatus
ON OrderStatus.OrderStatusId = LastOrder.OrderStatusId
+1  A: 

This should be equivalent:

from c in dc.Customers
join o1 in dc.Orders
on
new { o1.CustomerId,
        (from inner
         in dc.Orders
         where inner.CustomerId == c.CustomerId
         select inner.CreatedOn).Max()
    }
equals
new { c.CustomerId,
      o1.CreatedOn
    }
join o2 in dc.Orders
on
o1.OrderStatusId == o2.OrderStatusId
into joined
select joined
Rex M
Thanks I got this to work with some tweaks - I could not get this version to compile exactly do to scope issues. This is the equivalent of what I ended up using.from c in dc.Customersjoin o1 in dc.Ordersonnew { c.CustomerId,Createdon= (from inner in dc.Orders where inner.CustomerId == c.CustomerId select inner.CreatedOn).Max() }equalsnew { o1.CustomerId, o1.CreatedOn }into c01from z in c01.DefaultIfEmpty()join o2 in dc.Ordersonz1.OrderStatusId == o2.OrderStatusIdinto joinedselect joined
Jeremy Coenen
@Jeremy Coenen cool! Glad you got it working. I wrote it in the browser, so sorry for any mistakes.
Rex M