Welcome to Bilal Haidar [MVP, MCT] Official Blog Sign in | Join | Help

LEFT OUTER JOIN in LINQ To SQL

I was practicing a little bit on using Linq to Sql, and had this scenario:

Customers and Orders tables in Northwind Database. I added a new customer with no records, I wanted to apply a left outer join to get customers whose CustomerID starts with letter B such that, even if the Customer had no record in the Orders table, I wanted his/record to be present in the result.

The easiest way to go is to use LEFT OUTER JOIN between Customers' table and Orders' table so that I get all Customers that pass the filter expression and even have no records in the Order table, here is the Query Expression:

        NorthwindDataContext db= new NorthwindDataContext();
        var query=  from c in db.Customers
                    where c.CustomerID.StartsWith("B")
                    join o in db.Orders on c.CustomerID equals o.CustomerID into sr
                    from x in sr.DefaultIfEmpty()
                    select new {CustomerID= c.CustomerID, ContactName=c.ContactName, OrderID = x.OrderID == null ? -1 : x.OrderID};   

As you can see I used the join into operator in Query Expression which results in the LEFT OUTER JOIN, I added my filter expression in the where clause and finally, I returned an anonymous type containing CustomerID, ContactName, and OrderID which is -1 in case there is a null Order record for the Customer otherwise returns the OrderID.

The T-SQL representation of the above is as follows:

SELECT [t0].[CustomerID], [t0].[ContactName],
    (CASE
        WHEN [t1].[OrderID] IS NULL THEN @p1
        ELSE [t1].[OrderID]
     END) AS [value]
FROM [dbo].[Customers] AS [t0]
LEFT OUTER JOIN [dbo].[Orders] AS [t1] ON [t0].[CustomerID] = [t1].[CustomerID]
WHERE [t0].[CustomerID] LIKE @p0

Notice how the LEFT OUTER JOIN appears, notice how the CASE appears which reflect the if/else that I have added in the above Query Expression.

Hope this helps you!
Regards

 


You can make your own ringtones, for your cell phones; if those already set on your phones doesn’t suite you. You can download handy soft wares from electronics websites that help you make customized ringtones. These procedures carry very simple instructions still if you find some difficulty, you can use printers to print the instructions.
Published Wednesday, August 01, 2007 1:06 AM by BilalHaidar [MVP]
Filed under: , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: LEFT OUTER JOIN in LINQ To SQL

Good explanation. Thanks.

Tuesday, March 18, 2008 5:55 PM by James Price

# re: LEFT OUTER JOIN in LINQ To SQL

Wow, that has to be the dumbest, most complex syntax I have ever seen for something that should be trivial.

how about leftjoin and rightjoin anyone? MS I can't believe you punish us this much for using LINQ!

Monday, May 26, 2008 3:03 PM by James Hancock

# re: LEFT OUTER JOIN in LINQ To SQL

Thanks for your help!  This link also helped bring me up to speed on this topic: http://blogs.msdn.com/vbteam/archive/2008/01/31/converting-sql-to-linq-part-8-left-right-outer-join-bill-horst.aspx

Monday, June 02, 2008 1:58 PM by John

# re: LEFT OUTER JOIN in LINQ To SQL

It seems to me that code:

ar query=  from c in db.Customers

                   where c.CustomerID.StartsWith("B")

                   join o in db.Orders on c.CustomerID equals o.CustomerID into sr

                   from x in sr.DefaultIfEmpty()

                   select new {CustomerID= c.CustomerID, ContactName=c.ContactName, OrderID = x.OrderID == null ? -1 : x.OrderID};

will not work properly - Exception of type 'System.NullReferenceException : Object reference not set to an instance of an object' might fire.

May be the best way is replace the part of code <b>'OrderID = x.OrderID == null ? -1 : x.OrderID' </b> to next: <b>'OrderID = x == null ? -1 : x.OrderID'<b>

Tuesday, June 10, 2008 6:07 AM by wizalex

# re: LEFT OUTER JOIN in LINQ To SQL

I find mistake from "OrderID = x.OrderID == null ? -1 : x.OrderID". Could you check it again?

Thank alot!

Wednesday, November 05, 2008 6:03 PM by Tuantt

# re: LEFT OUTER JOIN in LINQ To SQL

wizalex is correct, you want:

OrderID = (x == null) ? -1 : x.OrderID

because in a left join if the value does not exist it will return null, which is what this line does:

from x in sr.DefaultIfEmpty()

in this case x can be (default) null and therefore you would not be able to reference x.OrderId

Monday, November 10, 2008 1:56 PM by Denny

# re: LEFT OUTER JOIN in LINQ To SQL

Hi Frnds

       I am using the same code with MySql like you.I am getting a error 'Lambda Parameter not in scope'

Please help me

Sunday, November 30, 2008 11:15 PM by Upender

# re: LEFT OUTER JOIN in LINQ To SQL

Love the variable naming ...."x" classic

Wednesday, January 28, 2009 8:51 AM by Nick

Leave a Comment

(required) 
required 
(required)