Thursday, July 14, 2011

Entity-Framework Differed loading (Lazy Loading) and immediate (Eager ) loading

You can use entity framework with lazy loading enabled to do everything . But when you try to do the performance testing you will find some crazy things going on inside. You can use SQL Server Profiler or a tool such as Entity Framework Profiler to see whats happening inside. By looking at SQL queries exacuting to ther server you can understand where to use Lazy loading or Immediate loading.
1.Lazy loading
Related entities are automatically loaded from the data source when you access a navigation property. With this type of loading, be aware that each navigation property that you access results in a separate query executing against the data source if the entity is not already in the ObjectContext. Here is a lazy loading enabled example
db.Configuration.LazyLoadingEnabled = true;// enable lazy loading
var student = db.Students.FirstOrDefault(st => st.PersonID == 1);// first queri will execute here
int i=student.Enrollments.Count;// Second query will execute here to load selected students enrolments

It will execute two separate queries to the server. First is to get student's sealer properties and second query is to load his enrollments.

2.Immediate/Eager Loading
In this type only one single request will go to the database. It will return all entities defined by the path in a single result set. You can specify the related data that you want to load with the query by specifying paths.
db.Configuration.LazyLoadingEnabled = false;
var student = db.Students.Include("Enrollments").FirstOrDefault(st => st.PersonID == 1);
int i=student.Enrollments.Count;

this will execute one query to load student's scaler properties and his navigational property(Collection of Enrollments).

How to choose the best method
You need to consider three things,

  1. How many connections that you are going to make with the database. If you are using lazy loading there will be a database call for all the reference points of a navigation properties if referred navigation property is not in the context.
  2. How much data that you are going to retrieve from databaseIf you choose to load all the data in initial query with differed loading it will be too slow when you have huge amount of data to retrieve.
  3. Complexity of the query . When you are using lazy loading the queries will be simple because all the data is not loaded in the initial query. If you use immediate loading it will make quires will be more complex with query paths

2 comments:

  1. The variable you mentioned as "db" is the instance of DbContext class I think.

    ReplyDelete