What is eager loading?

Technology CommunityCategory: Entity FrameworkWhat is eager loading?
VietMX Staff asked 3 years ago

The opposite of lazy loading is eager loading. In eager loading we load the objects beforehand. So the first thing is we need to disable lazy loading by setting LazyLoadingEnabled to false.

context.ContextOptions.LazyLoadingEnabled = false;

Now we have to explicitly tell EF what objects we want to load by using the include function. Below is a simple sample code where we tell EF to load customer as well as address objects by using the include function.

Now the customer object and the related address objects will be loaded in one query rather than multiple queries.

var employees = context.Customers.Include("Addresses").Take(5);