Loading related data

1 min read
On trails:EFCOREstep 3/8

EF Core gives you several ways to load the entities related to a queried entity.

Eager loading

Related data is loaded as part of the initial query, using the Include() and ThenInclude() methods. This typically results in a single, more complex query.

Explicit loading

Related data is loaded on demand at a later time, using methods like these:

C#
context.Entry(entity).Collection(e => e.RelatedCollection).Load()
context.Entry(entity).Reference(e => e.RelatedReference).Load()

Lazy loading

With lazy loading, related data is loaded automatically from the database when a navigation property is accessed for the first time. It requires installing the Microsoft.EntityFrameworkCore.Proxies package and configuring the navigation properties as virtual.

It’s convenient, but it can lead to the “N+1 query problem” if it’s not used carefully. Accessing a navigation property for N entities then results in N additional database queries. The query habits noteEF Core query habitsSix habits that keep EF Core queries fast.Opens in a new tab covers how to avoid it.


Sources