Can you explain lazy loading in a detailed manner ?

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 “customer” and “address” object.

Now let’s say you are browsing the customer data but you do not want address data to be loaded that moment. But the time you start accessing the address object you would like to load address data from database.

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

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

MyEntities context = new MyEntities(); 
var Customers = context.Customers.ToList(); 
foreach (Customer cust in Customers) // In this line no address object loaded 
  foreach(Address add in cust.Addresses)
    }// Address object is loaded here