2

I have a query that looks like this

         var query = db.Customer
            .Include(c => c.Address)
            .Where(c => c.Address.Id > 10)
            .ToList();

when i do this instead

        var query = db.Customer
            .Where(c => c.Address.Id > 10)
            .ToList();

        db.Address
            .Where(a => a.Id > 10)
            .Load();

I get the same result as far as I see.

My question is: is there any difference between what these two queries return and is one preferred over the other?

King Blob
  • 23
  • 4
  • Have you tried to search for duplicates "load vs include"? There are plenty, e.g. [here](http://stackoverflow.com/q/19319116/1997232). – Sinatr Nov 07 '16 at 11:05
  • I did, but obviously not good enough. But this case is slightly different, since I use Address in the first query before I Load it I wanted to know if this could cause any problem or the result of both methods would always be the same. – King Blob Nov 07 '16 at 12:13

1 Answers1

1
var query = db.Customer
                .Include(c => c.Address)
                .Where(c => c.Address.Id > 10)
                .ToList();

On above query where it brings all the related data using single database trip.

 var query = db.Customer
                .Where(c => c.Address.Id > 10)
                .ToList();

            db.Address
                .Where(a => a.Id > 10)
                .Load();

Here it uses 2 database trips to bring the data.

Load :

There are several scenarios where you may want to load entities from the database into the context without immediately doing anything with those entities. A good example of this is loading entities for data binding as described in Local Data. One common way to do this is to write a LINQ query and then call ToList on it, only to immediately discard the created list. The Load extension method works just like ToList except that it avoids the creation of the list altogether.

Note : We cannot say which one is better.Most of the time we use eager loading method (Include).It is nice and simple.But sometimes it is slow.So you need to decide which one to use according to your data size and etc.

Sampath
  • 63,341
  • 64
  • 307
  • 441
  • So both queries bring back the exact same data then? my code is a little bit different than this and when I look in SQL server profiler the first query has a little bit more reads than the second one, is that a good indication on which query I should use? Also you said the include method was eager loading, does the load method also have a name? – King Blob Nov 07 '16 at 11:08
  • which one is the fast ? – Sampath Nov 07 '16 at 11:10