Skip to main content

Inside Entity Framework: Lazy Loading, Explicit Loading and Eager Loading

When working with Entity Framework, it is important to understand how to hit the database and get the data especially to avoid the performance issues with the applications. That is exactly what I’m going to explain here that there are several ways to hit the database and load the related entities to retrieve the data. Also it is purely developer’s choice which one to use depending on the context to improve the performance.


Lazy Loading:

With lazy loading enabled, related objects are loaded when they are accessed through a navigation property. The default value of LazyLoadingEnabled is false. However, if we use the EF tools to create a new model and the corresponding generated classes, LazyLoadingEnabled is set to true in the object context's constructor by default. In this type of loading, each navigation property that we access causes a separate query to be executed against the data source.

Here is the simple example which is based on the assumption that there are three tables Organizations, Tenants and Facilities.
The relationship between these tables is :
Organization has multiple Tenants
Tenants have multiple Facilities

using (DatabaseEntities context = new DatabaseEntities())
{
context.ContextOptions.LazyLoadingEnabled = true;

var organizations = context.Organizations.Take(100);
var tenant = context.organizations.Where(org => org.TenantId == "T1").FirstOrDefault();

// If lazy loading was not enabled no Facilities would be loaded for the tenant.
foreach(Facilities facility in tenant.Facilities)
{
Console.WriteLine("FacilityID: {0}", facility.facilityID);
}
}

Explicit Loading:

The following example in this topic show you how to explicitly load related objects by using the LoadProperty method on the ObjectContext. In this the Lazy Loading is set to false and we load the related entities explicitly each time. This example is based on the assumption that there are four tables: organizations, tenants, Facilities and ApplicationInstances. The relationship between these tables is an organization has multiple tenants, the tenants have multiple facilities and the facilities in turn have multiple ApplicationInstances.

using (DatabaseEntities context = new DatabaseEntities())
{
context.ContextOptions.LazyLoadingEnabled = false; // Disable Lazy Loading
context.MergeOption = MergeOption.AppendOnly;

var organization = context.Organizations.Where(org => org.OrganizationId == “org1”).FirstOrDefault();
context.LoadProperty(organization, org => org.Tenants);

var tenants = organization.Tenants.Where(tnt => tnt.TenantId == "T1").FirstOrDefault();
context.LoadProperty(tenants, tnt => tnt.Facilities);

var facility = tenants.Facilities.Where(fac => fac.FacilityId == "F1").FirstOrDefault();
context.LoadProperty(facility, fac => fac.ApplicationInstances);

var applicationInstances = facility.ApplicationInstances.Where(appIns => appIns.ApplicationInstanceId == "AI1");

foreach(var item in applicationInstances)
{
Console.WriteLine("ApplicationInstanceID: {0}", item.applicationInstanceID);
}
}

Eager Loading:

There are circumstances that you may want only one query to hit the database and get the related entities rather than hitting every time. At times it may be a costlier operation to hit the database every time to load the related entities. In this scenario this Eager loading is very handy to do this operation. This example is based on the assumption that there are four tables: organizations, tenants, Facilities and ApplicationInstances. The relationship between these tables is an organization has multiple tenants, the tenants have multiple facilities and the facilities in turn have multiple ApplicationInstances.

DatabaseEntities context = new DatabaseEntities();
context.MergeOption = MergeOption.OverwriteChanges;

var organization = (from org in context.Organizations.Expand(tnt => tnt.Tenants.SubExpand(f => f.Facilities.
SubExpand(ai => ai.ApplicationInstances)))
where org.OrganizationId == "T1"
select org).First();

foreach (var tnt in organization.Tenants)
{
foreach (var facility in tnt.Facilities)
{
foreach (var item in facility.ApplicationInstances)
{
//Do Something
}
}
}

Comments

Popular posts from this blog

C# Generic Factory

Implement Factory pattern using generics     public interface IDoWork   {       string DoWork();   }     Declare an Interface first by abstracting the common  functionality    Here I am taking the example of DoWork     public class Manager : IDoWork   {     public string DoWork()     {         return "Manager Manages School" ;     }   }     Implement the IDoWork in concrete classes as shown      public class Teacher : IDoWork     {         public string DoWork()         {             return "Teacher teaches student in school" ;         }     }     public class Student : IDoWork     {         public string DoWork()         {             return "Study in school" ;         }     } This class will actually create an instance of the concrete class so that you can work on that        object further     public class FactoryDemo     {         public T Create

How to enable windows authentication in PostgreSQL

1.     Steps to create user or role in PostgreSQL ·         Open pgAdmin III ·         Login to PostgreSQL database ·         Select “Login Roles” and right click on mouse to view the context menu ·         Select “New Login Role” from context menu ·         Enter desired user name in “Role name” text box ·         Select “Definition” tab in “New Login Role” window ·         Enter desired Password in the given text box ·         Select “Role privileges” tab in “New Login Role” window ·         Select the privileges for the entered user or role ·         Select “SQL” tab in “New Login Role” window ·         This will display the auto generated script ·         Review the script and click on “OK” button ·         Now in the “Login Roles” the newly created role or user “newUser” is displayed ·         Now in pgAdmin III object browser select the database to which the newly created user should be ma

UML - Association, Aggregation, Composition, Generalization, Specialization, Realization and Dependency

Association Association is a simple relationship between two classes. For example A relationship between Professor Class and Student class is known as Association. Both Classes can exist without each other, so Professor and Student are two independent classes. In this kind of relationships there will not be any owner class. Both classes have their own life cycle. UML Notation:     Aggregation Aggregation is a special type of Association. It is known as “Has-A” relationship. For example A Department class can contain Professor Class. Here Department class is owner class. Here in this relationship even after deleting Department class, Professor Class can exits. UML Notation: Composition Composition is a special type of Aggregation. It is known as “Is-A” relationship. For example A University Class has many Department class. Here University and Department objects are dependent on each other. If we delete University cl