Search code examples
linqright-join

right join on my linq query


I want to return ALL items from db.Accounts. How do I do a right join on the below linq query?

        var query = (
                     from tradeTbl in db.Trades
                     join acctTbl in db.Accounts on tradeTbl.AccountID equals acctTbl.AccountID

I've tried changing to

        var query = (
                    from acctTbl in db.Accounts
                    join tradeTbl in db.Trades on acctTbl.AccountID equals tradeTbl.AccountID
                    where acctTbl.AccountActive == true

still not working... if I put that same query in SSMS and change it to LEFT JOIN it works in SSMS


Solution

  • Just write it in terms of a left (outer) join by reversing the joined tables.

    var query =
        from a in db.Accounts
        join t in db.Trades on a.AccountID equals t.AccountID into ts
        from t in ts.DefaultIfEmpty()
        select ...;