Skip to main content

Deferred Execution in Entity Framework

Original Article for reference 


Deferred Execution Vs Lazy Loading Vs Eager Loading Vs Explicitly Loading

  • Deferred Execution – “don’t compute the result until the caller actually uses it.”

Lazy loading and explicit loading are both types of deferred execution.
  • Lazy Loading – “don’t do the work until you absolutely have to.”

An entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. Related/child objects are not loaded automatically when a navigation property is accessed. When using POCO (Plain Old CLR Objects) entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook.
In case of Entity Framework, You can turn off the lazy loading feature by setting LazyLoadingEnabled property of the ContextOptions on context to false. This is very uselful when you are sure that you will need child object as well. 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.
context.ContextOptions.LazyLoadingEnabled = false;
When using POCO entity types, Lazy loading can be turned off by making the Posts property non-virtual:
1
2
3
4
5
6
7
public class Blog
{
     public int BlogId { get; set; }
     public string Name { get; set; }
 
     public <del>virtual</del> ICollection<Post> Posts { get; set; }
}
  • Eager Loading – “do all the work in advance”

A query for one type of entity also loads related/child entities as part of the query. Child objects are loaded automatically with its parent object when parent object is loaded.
In case of Entity Framework, You can achieve Eager loading by using ObjectQuery<T>.Include() method.
// Loads contacts, all related SalesOrderDetails
context.Contacts.Include("SalesOrderHeaders.SalesOrderDetails")
// Load all blogs, all related posts, and all related comments 
 var blogs1 = context.Blogs.Include(b => b.Posts.Select(p => p.Comments)).ToList();
  • Explicitly Loading – “do all the work even with lazy loading disabled”

Even with lazy loading disabled it is still possible to lazily load related entities, but it must be done with an explicit call. To do so you use the Load method on the related entity’s entry.
1
2
// Load the blog related to a given post
context.Entry(post).Reference(p => p.Blog).<strong>Load()</strong>;
1
2
3
4
5
6
// Load the posts with the 'entity-framework' tag related to a given blog
 context.Entry(blog)
     .Collection(b => b.Posts)
     .Query()
     .Where(p => p.Tags.Contains("entity-framework")
     .<strong>Load()</strong>;
  • Using Query to count related entities without loading them

1
2
3
4
5
// Count how many posts the blog has, without fetching/loading all the posts
context.Entry(blog)
     .Collection(b => b.Posts)
     .<strong>Query()</strong>
     .Count();

Comments

Popular posts from this blog

UML - Association, Aggregation, Composition, Generalization, Specialization, Realization and Dependency

Association Association is a simple relationship between two classes. For example A relationship between Professor Class and Student class is known as Association. Both Classes can exist without each other, so Professor and Student are two independent classes. In this kind of relationships there will not be any owner class. Both classes have their own life cycle. UML Notation:     Aggregation Aggregation is a special type of Association. It is known as “Has-A” relationship. For example A Department class can contain Professor Class. Here Department class is owner class. Here in this relationship even after deleting Department class, Professor Class can exits. UML Notation: Composition Composition is a special type of Aggregation. It is known as “Is-A” relationship. For example A University Class has many Department class. Here University and Department objects are dependent on each other. If we delete Univ...

C# Generic Factory

Implement Factory pattern using generics     public interface IDoWork   {       string DoWork();   }     Declare an Interface first by abstracting the common  functionality    Here I am taking the example of DoWork     public class Manager : IDoWork   {     public string DoWork()     {         return "Manager Manages School" ;     }   }     Implement the IDoWork in concrete classes as shown      public class Teacher : IDoWork     {         public string DoWork()         {             return "Teacher teaches student in school" ;         ...

Liskov substitution principle with simple example

Liskov Substitution Principle Definition 2 : Functions that use references to base classes must be able to use objects of derived classes without knowing it. Definition 2 : Object inheriting from base class or interface or other abstraction must be semantically substitutable for the original abstraction. Definition 3 : If a program module is using a Base Class, then the reference to the base class can be replaced with a derived class without affecting the functionality of the program module. Problem We all know that square is a rectangle from geometry. Now create a Rectangle base class with associated Height and Width properties and create Area() method to calculate the area in Rectangle base class.     public class Rectangle     {         public virtual int Height { get ; set ; }         public virtual int Width { get ; set ; }   ...