Search code examples
c#sqllinqlinq-to-dataset

LINQ To DataSet from SQL


I am having trouble converting a SQL Join statement into LINQ to DataSet. Also, consider that there will be other tables in the LINQ statement that the Header table will be joined to. Below is my Join statement - any help is appreciated.

FROM Header
LEFT JOIN Address
ON Header.Customer = Address.Customer
AND Header.Company = Address.Company
AND ((Header.ShipTo = 'TEMP' AND Header.DocNum = Address.ShipTo) 
    OR Header.ShipTo <> 'TEMP' AND Header.ShipTo = Address.ShipTo)

Solution

  • Doing a join in Linq uses the Equals() method. When using multiple columns, you'll have to create an identically structured anonymous type for comparison.

    from h in db.header
    join a in db.address
    on new { 
             cust = h.Customer, 
             comp = h.Company 
           } 
    equals new 
           { 
             cust = a.Customer, 
             comp = a.Company 
           }
    where ((h.ShipTo == "TEMP" && h.DocNum == a.ShipTo) 
            || h.ShipTo != "TEMP" && h.ShipTo == a.ShipTo)
    select h;