Jon Norton
Jon Norton

Reputation: 3009

Query with a join or use LINQ magic?

Is is better to do a joined query like this:

var employer = (from person in db.People
                  join employer in db.Employers
                  on person.EmployerID equals employer.EmployerID 
                  where person.PersonID == idPerson
                  select employer).FirstOrDefault();

Or is it just as good to do the easy thing and do this (with null checks):

var employer = (from person in db.People
                  where person.PersonID == idPerson
                  select person).FirstOrDefault().Employer;

Obviously, in this one I would actually have to do it in 2 statements to get in the null check.

Is there any sort of best practice here for either readability or performance issues?

Upvotes: 3

Views: 392

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1504062

I'd use this:

var employer = (from person in db.People
                where person.PersonID == idPerson
                select person.Employer).FirstOrDefault();

It's got the simplicity of the first version but still only fetches the data for the employer (rather than the person and the employer).

Upvotes: 6

Mitchel Sellers
Mitchel Sellers

Reputation: 63136

I find the first one better to read, but I am not sure of the differences in implementation.

I strongly recommend using LinqPad to see the Generated SQL that will help you figure out differences.

Upvotes: 1

David Basarab
David Basarab

Reputation: 73351

The second one could evaluate to null which would result in an error.

I like the first one better because if it is null then you can deal with it without an exception being thrown.

Upvotes: 1

Related Questions