65.9K
CodeProject is changing. Read more.
Home

Simplest Way to Make an OUTER JOIN in LINQ to Entity

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Jun 13, 2014

CPOL
viewsIcon

9606

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:

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!!

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!