King Blob King Blob - 1 month ago 10
C# Question

What is the difference between load and include in sql query

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?

Answer
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.