In the Entity Framework the lazy load ( Lazy Load ) is set by default. Assume 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 Produto
is loaded. When fetching data from Produto
, which is filled in ProdutoCategoria
and Fabricante
are classes of type DynamicProxy
. These entities will only become objects of their Models when they are accessed directly.
And what, after all, is a DynamicProxy ?
It is an object that pretends to be another (or, in this case, the object of a Model ). When it is accessed, the Entity Framework will effectively fetch the database from that object and DynamicProxy will become the Model object.
Technically speaking, the Entity Framework prepares 3 queries for the example:
- One for
Produto
itself;
- One for
ProdutoCategoria
;
- One for
Fabricante
;
Initially only the first one is fired. The others are only fired if objects are accessed.
What about Eager Load?
The Eager Load ), in the example, would load all the data at once. The Entity Framework, in this case, would only do one sentence with joins and soon after the transliteration of the results for their respective objects.
It is easy to note that in this way, any load of cardinality N leads to performance problems. Eager Load is only valid for cases where there are many relationships between tables from 1 to 1.