Lazy Loading in Entity Framework Core
Lazy Loading in Entity Framework is exactly what one would think it is, It is the process of delaying the loading of related data. This means that an entity/collection referenced is automatically loaded from your POCO. This feature has been a mainstay in EF 6, but only made its way to .NET Core in version 2.1.
How do achieve this?
For this post we are going to take the example of an E-Commerce domain. Say we have an Order and LineItem entities. Below we have the Order POCO entity:
Above we have the Order entity class with all it’s properties, but more than that we have another property that references a collection of LineItems from the LineItem entity. This means that the context will first load the Order and all its data from the database, but with Lazy Loading, it will also later load the LineItem entity from the database once the LineItems property is accessed. It is important that I also point out that the LineItems property is virtual, this is important as the Context will NOT do lazy loading if the property is not defined as such. See example below:
Lazy Loading is pretty much the default configuration so all you have to do is create these virtual entity references as I did with the LineItems property on the Order entity type. To turn if off you should make the property non-virtual, or you can turn it off across all your entities by setting the configuration setting to to false on your context. See below:
In the process of learning Lazy Loading, I also came across Eager Loading, essential Eager Loading is the opposite of Lazy Loading. It is the process of loading data from multiple entities at the same time. With Lazy Loading, you are loading the primary entity's data first (Order), but the referenced entity’s data will not be loaded until you explicitly access it (LineItems).
By using the Include method, we can eagerly load referenced entities. You could even go multiple levels deep in you query and load data from multiple referenced entities. In the example above I am loading Orders, On Orders, I am referencing the LineItems for said order and getting the result set of orders and LineItems all in one single query. For the example of going multiple levels deep, I also have a virtual Reviews property on the LineItem entity that references the Reviews submitted for a particular product. So On the LineItem, I can get a collection of reviews for said product, this is all executed in one query as well.
I highly recommend using Lazy Loading mostly because it will save you a lot of keystrokes and helps you keep in line with they DRY principle of not repeating yourself when querying your database.