Blog

Lazy Loading in Entity Framework

Lazy load is a pattern applied to delay loading of a resource until it is actually needed or accessed. For example, you may have an object that instantiates and initializes a logging utility in its constructor. The class may use the logger only in certain scenarios and often times it is not used at all. Given this attribute of the application, it would make sense to only load the logger when needed. One solution to this problem would be to implement the logger as a singleton and check to see if the logger has been previously initialized whenever a request to submit a log entry is sent. If the logger is not initialized, logic to initialize the logger is executed and the application proceeds as normal.

 

One of the benefits of using Entity Framework is that it implements lazy loading. This means that you can chain entity lambda expressions all day long, creating huge queries, but in the end Entity Framework will make sure that only objects being accessed are retrieved from the database.

 

Lazy loading is optional and can be turned off at the DatabaseContext:

 

        // Disable lazy loading

       Context.Configuration.LazyLoadingEnabled = false;

 

You may want to disable lazy loading to gain performance benefits and more control over the load behavior.

When taking this approach, it is still possible to load related entities by eager loading or explicit loading.

 

The eager loading approach will cause all related entities of a given entity to be loaded when the primary entity is loaded. For example, when loading a SalesOrder class that has many OrderItems, all OrderItems will be loaded automatically. This is done with a call to “Include()” on the primary entity:

 

        // Load all SalesOrders and related SalesOrdersItems

        var orders = context.SalesOrders

                              .Include(s => s.SalesOrderItems)

                              .ToList();

 

Explicit loading refers to loading related entities using explicit commands. This is accomplished using the “Load()” method on the related entities:

 

        var order = context.SalesOrders.Find(1);

 

        // Load the SalesOrdeItems related to a given SalesOrder

        context.Entry(order).Collection(p => p.SalesOrderItems).Load();

 

 

 

LINKS

https://msdn.microsoft.com/en-us/data/jj574232.aspx

http://martinfowler.com/eaaCatalog/lazyLoad.html