Enabling Lazy Loading in Entity Framework Code First Model

In Entity Framework you can configure several attributes for your Database Context class. In this article I will tell you what Is Lazy Loading and how you can leverage this feature in Code First Model.

Lazy Loading is a feature through which the Code First engine loads the navigation objects that belongs to the parent entity. For e.g. If there is a Person Entity and Person belongs to particular Department. Now when you load the Person retrieve the person object it will load the Department object values as well through which you can easily navigate to its properties and display those on forms or anywhere.

In order to enable Lazy Loading you can enable the properties values under your context constructor as follows.


public DemoContext()

{


this.Configuration.LazyLoadingEnabled = true;


this.Configuration.ProxyCreationEnabled = true;

}

 

One important point, lazy loading will only work if the ProxyCreationEnabled is enabled and the Navigation property of entity is virtual.

 


public
class
Person

{


public
Int32 Id { set; get; }


public
String Name { set; get; }

 


public
virtual
Department Department { get; set; }


public
Int32 DepartmentId { set; get; }

 


public
string Gender { set; get; }

}

 


public
class
Department

{


public
Int32 Id { set; get; }


public
String DepartmentName { set; get; }


public
virtual
ICollection<Person> Persons { set; get; }

}

 

Now, let suppose person table and department table have few records stored. When you read the Person using context.ToList () or any other linq function it will automatically load the department objects as well.

Develop a function that returns the list.

public
Person GetPerson(int id)

{


DemoContext context = new
DemoContext();

{


var items = context.Persons.Where(i => i.Id == 1);


return items;

}

}

 

Now, by adding a watch on Items you can see that you will get corresponding Department values i.e. DepartmentName and Id as well.


Therefore, Lazy loading helps developer to retrieve the child objects rather making joins in Linq query and automatically do the join part.

Happy Coding!

Advertisements

One thought on “Enabling Lazy Loading in Entity Framework Code First Model

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s