Getting Started with Entity Framework 4 – Lazy Loading

Entity Framework v1 did not support a commonly implemented ORM feature called Lazy Loading. Entity Framework 4 adds that feature. In Beta 1 it was known (confusingly IMHO) as Deferred Loading. In Beta 2 it is (thankfully IMHO) known as Lazy Loading.

You run up against the absence of Lazy Loading in v1 when you start moving across associations between Entities (Objects). Imagine for instance you had an instance of Order from Northwind and wanted to access its Order_Details, perhaps to do something as simple as return a count of the number of Order_Details.

You would be tempted to write:

order.Order_Details.Count

However this will return 0 unless you have already explicitly loaded the related Order_Details into the ObjectContext.

In v1 you could either explicitly project in your query (stating up front that you were interested in the count of Order_Details) or you could use explicit loading :

Orders.Include(“Order_Details”)

Either approach would ultimately give you the correct value instead of a dreaded 0.

However Lazy Loading ensures that in situations like the above, “It just works” and the beauty is that it requires a single statement to turn it on.

context.ContextOptions.LazyLoadingEnabled = true;

The following example performs the same operation, first with Lazy Loading off, then with it on:

image

Will product the output:

image

In a future post I will talk about the hidden dangers of LazyLoading and compare it to other ORM implementations.

This article is part of the GWB Archives. Original Author: Eric Nelson

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.