Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / entity-framework

Simplest Way to Make an OUTER JOIN in LINQ to Entity

5.00/5 (1 vote)
12 Jun 2014CPOL 9.6K  
The title says it all! Make an outer join in 1 LINQ statement

Introduction

Here, I will show how to write an OUTER JOIN in LINQ to SQL in the simplest fashion (one line)!

Using the Code

Let's say you got the following class in your Entity Framework model:

C#
public class Product
{
    public int ID { get; set; }
    public string Name { get; set; }
}
class Comment
{
    public int ID { get; set; }
    public int ProductID { get; set; }

    public string Text { get; set; }
}

And let's say you would like to get a product and the first comment or null, i.e., make an outer join...

Fear not, it's easy indeed!!

SQL
from p in ctx.Products
let c = (from c in ctx.Comments where c.ProductID == p.ID select c).FirstOrDefault()
select new { p, c }

This will make an outer join statement!

Points of Interest

I keep discovering everyday that LINQ to SQL / Entity is better than I thought!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)