EF Core Loading
EF Core Loading
Lazy Loading
Eager Loading
Explicit Loading
Keivan Damirchi
Lazy Loading
Lazy Loading is a technique where related data is only loaded
from the database when it is actually needed.
In other words, related data is not loaded until it is accessed. This is the
default behavior in EF Core, and it can be enabled by making the
navigation property virtual. Lazy Loading can cause performance issues,
as it can result in a large number of database queries being executed if not
used properly.
Example:
Suppose we have two entities, a "Book" entity and an "Author" entity, and they
have a one-to-many relationship where each book has one author. With lazy
loading, we can retrieve a book from the database and then access its author
property. EF Core will then execute a separate query to retrieve the author
from the database.
1
When to use
Lazy Loading?
Note
Lazy loading can result in a large number of database
queries being executed, known as the N+1 problem, if
accessed in a loop or when the navigation property is
accessed multiple times.
2
Eager Loading
Eager Loading is a technique where related data is
loaded from the database at the same time as the main
entity. This is achieved by using the "Include" method
to specify which related entities to load. Eager Loading
can improve performance by reducing the number of
database queries required.
Example:
Eager Loading is a technique where related data is loaded from the database
at the same time as the main entity. This is achieved by using the "Include"
method to specify which related entities to load. Eager Loading can improve
performance by reducing the number of database queries required.
3
When to use
Eager Loading?
Note
Eager Loading can result in unnecessary data being loaded, especially
when there are complex navigation properties or large datasets, leading to
decreased performance.
4
Explicit Loading
Explicit Loading is a technique where related data is
loaded from the database on an as-needed basis, but
the loading is initiated explicitly using the "Load"
method. This can be useful when you want to load
related data for only a subset of entities and do not
want to load all related data at once.
Example:
Using the same Book and Author entities, we can use Explicit Loading to
load an author for a book that has already been retrieved from the database
5
When to use
Explicit Loading?
Note
Explicit Loading requires additional code to be written to trigger the
loading of related data, and it can result in additional database queries
being executed if not used properly.
6
Close();
Keivan Damirchi