How Lazy Load Entity Framework works

12

It's the following personal, so I saw in Entity to use Lazy Load you leave the property without the virtual keyword , and eager with the virtual.

However, I have seen in some blog posts that staff use the Configuration.EnableLazyLoading = false/true; to enable or disable Lazy Load .

I was wondering how this issue works in Entity , thank you!

    
asked by anonymous 09.06.2014 / 19:36

1 answer

17

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.

    
09.06.2014 / 20:48