4

I have tableA and tableB.
I would like to perform left join using lambda expression. This is the equal sql statement:

SELECT *
FROM tableA A
    LEFT JOIN tableB B ON A.userId=B.userId

How can I do that using lambda expression?

1

1 Answer 1

5

It's usually an error to use an explicit join in LINQ to Entities.

Instead, use the navigation properties:

var q = Context.TableAs.Select(a => new { a.Foo, a.TableB.Bar });

LINQ to Entities will coalesce null references. So if a.TableB is null for some record in TableAs, then a.TableB.Bar will return null instead of giving you a null reference exception. So it behaves like a SQL LEFT JOIN

Sign up to request clarification or add additional context in comments.

5 Comments

@Naor: Usually, the right thing to do is to add them. You should use explicit joins mostly only if you can't add them for some reason.
@Naor: Like I said, mostly, you don't. You haven't yet convinced me that you have a good reason to omit navigations. Navigations are the right way to relate entities.
@Craig Stuntz: What about the desire to learn? How can I do left joins in lambda syntax?
@Naor: That's a different question. You asked how to do it with L2E. The right way to do it in L2E is to use navigations. You want to do it in L2O, then you can use Join() with a DefaultIfEmpty() on the "right" sequence. But don't do that for L2E, normally.
I have inherited a db that joins several tables without using any keys. (Before anyone weighs in with comments about that - I already know and as soon as I can replace the POS I will, but atm I can't.) And I can't create Navigations without them, so I have to do joins in code, and my personal preference is to use Lambda, in C# it makes more sense to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.