Can you explain lazy loading in a detailed manner?

Technology CommunityCategory: Entity FrameworkCan you explain lazy loading in a detailed manner?
VietMX Staff asked 3 years ago

Lazy loading is a concept where we load objects on demand rather than loading everything in one go. Consider a situation where you have 1 to many relationships between the Customer and Address objects. Now let’s say you are browsing the customer data but you do not want address data to be loaded at that moment. But the time you start accessing the address object you would like to load address data from the database.

Entity Framework has lazy loading behavior by default enabled. For instance, consider the below code. When we are doing a foreach on the Customer object, the Address object is not loaded. But the time you start doing foreach on the address collection, the Address object is loaded from SQL Server by firing SQL queries.

So in simple words, it will fire a separate query for each address record of the customer, which is definitely not good for a large number of records.

MyEntities context = new MyEntities();

var Customers = context.Customers.ToList();

foreach (Customercust in Customers) // In this line no address object loaded
{
     foreach(Address add in cust.Addresses){}// Address object is loaded here
}