Entity Framework: Different loading capabilities

Ralph Jansen BlogThe Entity Framework is in the new stage of evolving. We are now in stage 4.1 where the Code First functionality is released. Entity Framework enables just like LINQ to SQL different kind of loading types. But what are the loading types and what are the different capabilities? In this blog I will explain in a simple way what they are and what they can do.

There are 3 different kind of loading types for related data called lazy, Eager and explicit loading. In the next example you see two entities which are related.

image

Department can have many Courses and a Course can only have one Department.

Lazy Loading:
image 

 

Eager Loading:
image

 

Explicit Loading:
image

Because they don’t immediately retrieve the property values, lazy loading and explicit loading are also both known as deferred loading.

In general, if you know you need related data for every entity retrieved, eager loading offers the best performance, because a single query sent to the database is typically more efficient than separate queries for each entity retrieved. For example, in the above examples, suppose that each department has ten related courses. The eager loading example would result in just a single (join) query. The lazy loading and explicit loading examples would both result in eleven queries.

On the other hand, if you need to access an entity’s navigation properties only infrequently or only for a small portion of a set of entities you’re processing, lazy loading may be more efficient, because eager loading would retrieve more data than you need. Typically you’d use explicit loading only when you’ve turned lazy loading off. One scenario when you might turn lazy loading off is during serialization, when you know you don’t need all navigation properties loaded. If lazy loading were on, all navigation properties would all be loaded automatically, because serialization accesses all properties.

Leave a Reply