Updated March 15, 2023
Introduction to Entity Framework Lazy Loading
Entity Framework Lazy Loading is the process of an entity or the collection of entities that automatically loads the data from the database at the initial stage when the property refers to the particular entity accessed. Lazy Loading defines the associated data loads from the database only when the navigation property is accessible; it delays loading data until we request it.
Overview of Entity Framework Lazy Loading
In Entity Framework, Lazy Loading is the default behavior, which means that the associated entities are loaded at the initial stage of the execution when it is accessed; in other words, it delays loading the entity until we purposely request it.
Entity Framework maintains three methods of Loading related data they are:
- Eager Loading
- Lazy Loading
- Explicit Loading
Lazy Loading defines the collection of an entity that routinely loads the data from the database the first time the property refers to the particular entity accessed. Lazy Loading determines that the detailed data directly loads from the database if the navigation property is accessible. Entity Framework Lazy Loading is the technique that postpones loading the entity or the collection of the entity until the application essentially requires it and until we can turn off the particular property without defining the property as virtual.
There are specific rules to be followed by the Lazy Loading; they are as follows:
- We need to set the property true for context.Configuration.ProxyCreationEnabled.
- We need to set the property true for context.Configuration.LazyLoadingEnabled.
- For accessing the Lazy Loading, the navigation property must be defined as public and virtual; for disabling the Lazy Loading, the property should not be defined as virtual.
Entity Framework Lazy Loading Class
Lazy Loading defines detailed data directly loading from the database if the navigation property is accessible.
Let’s see one example for better understanding; see the below program; the ProductMaster entity is created from the EF; in the same class, you can see the Navigation Property for the CustomerMaster entity and the entities PSCart and the collection Navigation Property for orders.
Code:
using System;
using System.Collections.Generic;
public partial class ProductMaster
{
public ProductMaster ()
{
this.POrders = new HashSet<POrder>();
}
public int pmProdID { get; set; }
public string pmProdName{ get; set; }
public string pmProdDesc{ get; set; }
public string productCustz { get; set; }
public int pmProdCost{ get; set; }
public Nullable<System.DateTime> CDate { get; set; }
public virtual CustomerMaster CustomerMaster { get; set; }
public virtual PSCart PSCart { get; set; }
public virtual ICollection<POrder> POrders { get; set; }
}
In the above program with the Lazy Loading, the context initially executes or loads the ProductMaster entity data from the database. Then it will execute the other related entities when accessing the navigation properties.
Let’s see one example; look at the below statement while executing the code. The context will initially load the ProductMaster table and not execute the other tables like CustomerMaster, PSCart, or POrders data.
Code:
ProductMaster _product=context.ProductMasters.FirstOrDefault(p=>p. pmProdID==1001);
Once the statement is executed, the below statement will be completed, and the context will load the CustomerMaster table data as follows.
Code:
CustomerMaster custMaster= _product.CustomerMaster;
Next, the same way the below statement will be executed, the context will load the related PSCart table data.
Code:
PSCart shopCart=_product.PSCart;
Let’s see the entire example code given below as follows.
Code:
using System;
using System.Linq;
namespace EF_LLoading
{
class SampleEFProgram
{
static void Main(string[] args)
{
using (EFDBEntities efcontext = new EFDBEntities())
{
//initially it loads the particular product data only
ProductMaster _product = context.ProductMasters.FirstOrDefault(p => p.pmProdID==1001);
Console.WriteLine($"ProductName: {_product.pmProdName}, ProductDesc: {_product.pmProdDesc}");
//next it loads the customer
CustomerMaster custMaster= _product.CustomerMaster;
Console.WriteLine($"CustomerName: {custMaster.custName}, CustomerAddress {custMaster.Address}");
//next it will loads the shoppint cart details
PSCart shopCart=_product.PSCart;
Console.WriteLine($"NoOfProducts: {shopCart.totalItems}, Cost: {shopCart.totalCost}");
//and next it loads the order details
var OrderDetails = _product.porders;
foreach(var val in OrderDetails)
{
Console.WriteLine($"Orders: {val.Status}");
}
Console.Read();
}
}
}
}
Entity Framework Lazy Loading Turning Off
Entity Framework Lazy Loading has an option for enabling and disabling lazy Loading. For example, we can turn off the Lazy Loading for a particular entity or the entire entity (context).
Let’s see with an example to turn off the Lazy Loading for a particular entity. Turning off the lazy Loading for the desired entity is the main thing: don’t make the specific property virtual. Check with the previous sample program; they are lazy loads.
Code:
public virtual CustomerMaster CustomerMaster { get; set; }
public virtual PSCart PSCart { get; set; }
public virtual ICollection<POrder> POrders { get; set; }
To make those properties turn off the lazy Loading, we need not specify the property as non-virtual. To make non-virtual means disabling the Lazy Loading.
Let’s see with an example as follows:
Code:
public CustomerMaster CustomerMaster { get; set; } // Non-Virtual –Disabling Lazy Loading
public virtual PSCart PSCart { get; set; }
The Lazy Loading is disabled for the CustomerMaster property in the above codes. As a result, it will not load the CustomerMaster property while you call the CustomerMaster navigation property.
Code:
using System;
using System.Linq;
namespace EF_Disabling_LLoading
{
class Sample_UnLoading
{
static void Main(string[] args)
{
using (EFDBEntities efcontext = new EFDBEntities())
{
ProductMaster _product = context.ProductMasters.FirstOrDefault(p => p.pmProdID==1001);
Console.WriteLine($"ProductName: {_product.pmProdName}, ProductDesc: {_product.pmProdDesc}");
CustomerMaster custMaster= _product.CustomerMaster;
if(custMaster ==null)
{
Console.WriteLine("Customer Data is not Loaded!");
}
else
Console.WriteLine($"CustomerName: {custMaster.custName}, CustomerAddress {custMaster.Address}");
Console.Read();
}
}
}
}
To turn off for the entire entities by specifying all entities to set the flag as false to configuration property as shown below:
Code:
public partial class GtestEntities : DbContext
{
public GtestEntities()
: base("name=GtestEntities")
{
this.Configuration.LazyLoadingEnabled = false; // to turn off Lazy-Loading for all entities
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
Conclusion
Entity Framework is a Cross-Platform Light-weighted version that offers access to the data from data sources. In addition, it supports Lazy Loading, which loads and unloads the data from the database depending on the property.
Recommended Articles
We hope that this EDUCBA information on “Entity Framework Lazy Loading” was beneficial to you. You can view EDUCBA’s recommended articles for more information.