Lazy loading with DbContext

Description and code samples
Table of Contents

How it works

Entity Framework achieves lazy loading using a dynamic proxy:

When Entity Framework returns the results of a query, it creates instances of the classes and populates them with the data that was returned from the database.

Entity Framework creates dynamically a new type at runtime that derives from the original POCO class.

This new class acts as a proxy to the original POCO class and is referred to as a dynamic proxy. It will override the navigation properties of the POCO class and include some additional logic to retrieve the data from the database when the property is accessed.

What is required

In order to use dynamic proxies, and therefore lazy loading, the following must criteria must be meet for eact entity class:

  • The original POCO class must be public and not sealed.
  • The navigation properties to be lazy loaded must also be marked as virtual (overridable in Visual Basic) so that Entity Framework can override the properties to include the lazy loading logic.


How to configure

DbContext has a configuration setting that enables lazy loading:


This setting is configured by default to True and therefore if not overrided, the dynamic proxy will perform lazy loading.

Lazy loading sample
How to do it
using (var context = new BreakAwayContext())
    var query = from d in context.Destinations
                where d.Name == "Grand Canyon"
                select d;

    var canyon = query.Single();

    Console.WriteLine("Grand Canyon Lodging:");
    if (canyon.Lodgings != null)
      foreach (var lodging in canyon.Lodgings)

As the code is executed, Entity Framework will send two queries to the database:

Lazy loading query

The first query retrieves data for the entity  when the Single() method is executed – a SELECT TOP(2) statement is execute to ensure that only one item exists to be retrieved.

The second query select all the associated “lodgings” to the main entity object ” destination”. This query is only executed when the navigation property is accessed on the iteration code block.