0

I have the following Table Structure

Orders
 OrderID PK

PartyAddresses
 PartyAddressID PK

Then I have a join table that joins PartyAddress to a order

OrderAddresses
 OrderAddressID PK
 OrderID FK to Orders
 PartyAddressID FK to PartyAddresses
 AddressType  

The sql statment I am trying to convert is

SELECT 
 * 
FROM 
Orders o  LEFT JOIN OrdersAddresses oa
       ON 
    o.OrderID = oa.OrderID
       LEFT JOIN PartyAddresses pa
          ON
       pa.PartyAddressID = oa.PartyAddressID
WHERE
    oa.AddressType = 'SHIP'

I am having trouble figuring out to replicate this into Linq lambda statements

I have been been able to retrieve the data I want by starting at the OrdersAddress table

OrdersAddresses.Include("Orders").Include("PartyAddresses").Where(oa=>oa.AddressType=="Ship");

But I need the results in terms of a IEnumerable<Orders>

Update

I guess to rephrase my question - given the following repository function

public IQueryable<Orders> OrdersWithAddresses()
{
    return _context.Orders.Include("OrdersAddresses").Include("OrdersAddresses.PartyAddresses");
}

How would i add to the expression tree to only actually return order addresses that are "SHIP"

1 Answers1

0

This is off the top of my head but I believe it should work. Note that I've removed the first LEFT JOIN as it is just as easy to do a normal join due to the WHERE clause filtering out the NULLs anyway:

var results = from o in db.Orders
              join oa in db.OrdersAddresses on o.OrderID equals oa.OrderID
              join pa in db.PartyAddresses on oa.PartyAddressID equals pa.PartyAddressID into pas
              from p in pas.DefaultIfEmpty()
              where oa.AddressType == "SHIP"
              select new { o, oa, p };

Update:

Alternatively you can modify your repository function to include a Where clause:

public IQueryable<Orders> OrdersWithAddresses(Func<Orders, bool> predicate)
{
    var orders = _context.Orders.Include("OrdersAddresses").Include("OrdersAddresses.PartyAddresses");

    if(predicate != null)
        return orders.Where(predicate);

    return orders;
}

And call the function like this:

var orders = OrdersWithAddresses(o => o.AddressType = "SHIP");
DavidG
  • 113,891
  • 12
  • 217
  • 223