Getting Started with Entity Framework 4 – Lazy Loading

[This is the fifth in a series of posts on getting started with the new features in Entity Framework 4 based on the demos I did in my session at TechEd Europe in Berlin last week (Nov 2009).]

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:


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 :


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;

Check out my primary blog for a simple code sample.