- Ensure the proxy creation is on for the Context.
- Ensure the lazy loading is turned on.
- Make sure the class is not Sealed and is Public
- Declare the navigation properties you want to Lazy Load as Virtual
Example:
// Proxy creation
this.ContextOptions.ProxyCreationEnabled = true;
// Lazy Loading.
this.ContextOptions.LazyLoadingEnabled = true;
public class Customer
{
public string CustomerID { get; set; }
public string CompanyName { get; set; }
List<Order> orders = new List<Order>();
public virtual List<Order> Orders
{
get
{
return orders;
}
set
{
orders = value;
}
}
}
Once the above things are taken care of, lazy loading is ready to run in an application.
If you have a program which loads Customer and if you iterate through each order for a Customer, each Order in customer will load only when it is accessed from the customer as a navigational property. For example, if the customer has 5 orders, you could see 6 queries if you observe in the SQL Profiler. First query to load the Customer and the rest 5 queries, to load the Orders in the Customer when they are accessed through navigational property from Customer.
Note: If you wonder how can a plain object gets the power to lazy load, like an invisible event getting triggered to load it by itself, the answer is,
Once you set the navigational property as virtual, and the right settings are On for the context, entity framework overrides the plain object navigational property with its Entity Framework Proxy Object for that navigational property type, which is capable of calling the context and getting its values filled when it is accessed from the class.