Lazy Loading
- It is the process that automatically loads the data of a navigation property from the database the first time that it is accessed.
- When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook.
- In the following example, Student class contains StudentAddress as a complex property.
- Context first loads all the students from the database, then it will load the address of a particular student when we access StudentAddress property.
db.Configuration.LazyLoadingEnabled = true;
var student = db.Students.First();
// Loads Student address for the current Student (Executes seperate SQL query).
var address = student.StudentAddress;
Rules for Lazy Loading
context.Configuration.ProxyCreationEnabled
should be true.
context.Configuration.LazyLoadingEnabled
should be true.
- Complex property should be defined as
virtual
.
- Context will not do lazy loading if the property is not define as
virtual
.
Turn lazy loading off for serialization
- Lazy loading and serialization don’t mix well, and if you aren’t careful you can end up querying for your entire database just because lazy loading is enabled.
- Most serializers work by accessing each property on an instance of a type.
- Property access triggers lazy loading, so more entities get serialized.
- On those entities properties are accessed, and even more entities are loaded. It’s a good practice to turn lazy loading off before you serialize an entity.
Turning off lazy loading for specific navigation properties
- Lazy loading of a collection can be turned off by making the property non-
virtual
.
- Loading of the collection can still be achieved using eager loading or the
Load
method.
Turn off lazy loading for all entities
- Lazy loading can be turned off for all entities in the context by setting a flag on the Configuration property.