How to perform left join in linq to Entities

To perform left outer join in a linq query, you would normally use DefaultIfEmpty operator. DefaultIfEmpty opreator basically gives you a default instance of an object when there is no related record found. In version 1 of Entity Framework, DefaultIfEmpty was not supported, therefore you had to apply different techniques to get around this problem. I am very happy to see that DefaultIfempty is finally supported in Entity Framework version 4. Let’s walk through an example of how to use DefaultIfEmpty operator to get a left join.

Suppose you have an existing model consisting of Users and their LogDetails as shown below.

image

 

We want to display a flatten list of all users along with their LoginDate. We want to ensure that all users are displayed regardless if they have an entry in the Log table or not. To accomplish that we need to use DefaultIfEmpty operator to perform a left join. Code below shows the code.

 image

On the above code, we are casting LoginDate to nullable DateTime. This is to accommodate users who do not have any entry in the Login table. Thus by having LoginDate as nullable, users with no logindate can be assigned null.

Figure below shows the output of the above query.

image

3 Comments

Comments have been disabled for this content.