When using an object-relational mapper (ORM) like Entity Framework Core, the ASP.NET Core Web API supports both lazy loading and eager loading as two distinct methods for loading related entities in an object graph. Examining each strategy in turn.
1. Lazy Loading:
Related entities are not explicitly accessed before being loaded from the database using the method known as lazy loading. With less data being downloaded from the database, efficiency is improved since you may access the primary entity without loading any of its dependent entities. The ORM will automatically send a query to the database to retrieve the pertinent data whenever you access a navigation property of an entity.
To enable lazy loading in Entity Framework Core, you need to install the Microsoft.EntityFrameworkCore.Proxies
package and configure your context to use lazy loading proxies. Here's an example:
public class YourDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLazyLoadingProxies(); // Enable lazy loading
}
// ...
}
By default, lazy loading is disabled in Entity Framework Core to promote explicit loading and prevent potential performance issues caused by unintentional lazy loading.
2. Eager Loading:
A single query is used for eager loading, which involves loading the main entity as well as all linked entities. The quantity of database roundtrips is decreased because you can get all the necessary data upfront. When you anticipate needing the corresponding data and wish to avoid the performance overhead of lazy loading, eager loading is advantageous.
You can define related entities to be eagerly loaded in Entity Framework Core by using the 'Include' function. As an illustration, consider the following.
// Fetch a list of customers with their orders
var customers = context.Customers
.Include(c => c.Orders)
.ToList();
In this example, the Orders
navigation property of the Customer
entity is eagerly loaded along with the customers themselves.
Eager loading can be further customized using the ThenInclude
method to load multiple levels of related entities.
// Fetch customers with orders and order items
var customers = context.Customers
.Include(c => c.Orders)
.ThenInclude(o => o.OrderItems)
.ToList();
In this example, both the Orders
and OrderItems
navigation properties are eagerly loaded.
Both lazy loading and eager loading have their pros and cons, and the choice depends on your specific requirements and performance considerations.
Top comments (1)
Loved the concise overview of lazy loading and eager loading in Entity Framework Core. The 'Include' function rocks! Thanks for sharing!