Click here to Skip to main content
Click here to Skip to main content

Simplest Way to Make an OUTER JOIN in LINQ to Entity

, 12 Jun 2014
Rate this:
Please Sign up or sign in to vote.
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!

License

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

About the Author

Super Lloyd
Software Developer (Senior) http://www.radicalsystems.com.au
Australia Australia
The Australia born French man who went back to Australia later in life...
Finally got over life long (and mostly hopeless usually, yay!) chronic sicknesses.
Worked in Sydney, Brisbane, Darwin, Billinudgel, Darwin and Melbourne.
Follow on   Twitter

Comments and Discussions

 
SuggestionTyping mistake PinmemberMember 1079895916-Jun-14 20:53 
GeneralRe: Typing mistake PinmemberSuper Lloyd16-Jun-14 23:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 13 Jun 2014
Article Copyright 2014 by Super Lloyd
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid