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

About Cennest
Cennest is the brainchild of a group of IT Professionals keen to try their hand in the world of IT Freelancing. After working in the corpora

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

  1. Julie Lerman says:

    Your warning about lazy loading is not quite right. Lazy loading doesn’t cause EF to eager load (or pre-load) all of the navigations of order when you query for order. It will only bring back what you ask for in the query: Order.

    When you are using that Order in memory, if you make mention of “LineItems” e.g.,

    var itemCount=myorder.LineItems

    then lazy loading will kick in and go retrieve those lineitems from the database.

    You still need to be careful about lazy loading, aware of its behavior and in many cases, as you have suggested, take over the explicitly control and use Load or LoadProperty. I’m more of a fan of explicity loading myself. But I think you have raised an inaccurate alarm.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: