Eager & Lazy Loading – Entity Framework

Eager loading is the process of loading the relational data at one instance. Lazy loading is the process of loading relational data when needed (on demand basis). The entity frame work supports both eager and lazy loading patterns.

In below figure the Department and Employee are having a one-to-many relationship. Let us see how we can achieve eager/lazy loading using below entities.

Data in the tables

Eager Loading:

When we run the above code, and inspect using SQL profiler the below query has executed against the database.

The query is not loading any relational data i.e. employee table data. In order to load the relational data we have to use Include() Method as shown below.

On executing above code, below query will be executed against DB

When using eager loading all the relational data is loaded at once. The above query will be loading the tbldepartment data and also its relational data i.e. tblemployee data.

We can also load multiple tables data using ‘,’ separator as shown below

Lazy Loading:

As discussed above, it is the process of loading the relational data when needed (on demand basis). Let us analyze lazy loading using below code

When the line 13 is executed the below query got executed against the database

Once line 17 got executed we are trying to access employees under that department. But the department data was not loaded as part of the previous DB call. So now a new query will be executed against DB for fetching the required data.

Below three queries are executed against the database for fetching the tblEmpolee data

Conclusion

In case of eager loading only one call will go to DB and it fetches all the required relational data but in case of lazy loading the data is loaded only when needed therefore making multiple calls to DB.

Configuring Lazy Loading

Lazy loading is enabled by default. The best place to enable/disable lazy loading globally would be in the DBContext constructor as shown below

You can also disable/enable lazy loading when and where required as shown below

This way lazy loading is only disabled for this db scope.

Sample Code

DB script file is included in the solution

https://github.com/KishoreIthadi/Blog-Samples/tree/master/EntityFramework/Eager-Lazy-Loading

Happy Coding 🙂

Please leave a comment below, and let me know what you think!

About the Author

Kishore Ithadi

https://in.linkedin.com/in/kishoreithadi

Leave a Reply