In Entity Framework the lazy load (Lazy Load) is configured by default. Suppose a Product Model as the example below:
public class Produto
{
[Key]
public Guid ProdutoId {get;set;}
public Guid ProdutoCategoriaId {get;set;}
public Guid FabricanteId {get;set}
[Required]
public String Nome {get;set;}
public virtual ProdutoCategoria ProdutoCategoria {get;set;}
public virtual Fabricante Fabricante {get;set;}
}
In this case, ProdutoCategoria
and Fabricante
are not loaded when a Produto
is loaded. When fetching data from Produto
, which is completed in ProdutoCategoria
and Fabricante
are classes of the type DynamicProxy
. These entities will only become objects of their Models when they are directly accessed.
And what is, after all, a Dynamicproxy?
It is an object that pretends to be another (or, in this case, the object of a Model). When accessed, the Entity Framework will effectively search the database for the data of this object and the Dynamicproxy will become the object of Model.
Technically speaking, the Entity Framework prepares 3 queries for the example:
- One to the
Produto
in itself;
- One to
ProdutoCategoria
;
- One to
Fabricante
;
Initially only the first one is fired. The others are fired only if the objects are accessed.
And the Eager Load?
The charge in advance (Eager Load), in the example, it would load all the data at once. Entity Framework, for this case, would do only one sentence with joins and shortly after the transliteration of the results to their respective objects.
It is easy to notice that in this way, any load of cardinality N causes performance problems. The Eager Load applies only to cases where there are many relationships between tables from 1 to 1.
Favorite. I’ll be right back.
– Leonel Sanches da Silva
You reversed the explanation of the use of
virtual
.– iuristona