EF 4.0 Bulb Flash!:- Load only what you need!!

A small tip for those working with Entity Framework 4.0:- We all know the concept of Lazy Loading in the Entity Framework: With lazy loading enabled, related objects are loaded when they are accessed through a navigation property.

With lazy loading a drawback is that an object retrieved from the database comes loaded with all its navigable Objects so you may be querying an “Order” class but it comes loaded with the Order.Customer object .

[Thanks to Julielerman for pointing out this inconsistency.  Lazy Loading loads related entities on Navigation and does not come “loaded” with them]

While you may want this in some cases, it makes sense to disable this feature in performance oriented applications and load only what you need!

As against what is written in MSDN , our experience is that when an entity context object gets created, its LazyLoadingEnabled property is defaulted to true!… This is also a reported issue with microsoft

So first step would be to disable the LazyLoadingEnabled!

ProgramEntities entityContext = new ProgramEntities();
entityContext.ContextOptions.LazyLoadingEnabled = false;

List<Order> orderList= entityContext.Orders.ToList();

Next, load what you need!

orderList.ForEach(p => entityContext.LoadProperty(p, "Customer"));

Now you can access the Customer as Order.Customer while ensuring you did not load other related  navigable properties like Order.Contents etc etc.

Hope this helps “lighten” up your code a bit!!

Cennest !!

Advertisements