Why do navigation properties need to be declared as virtual? [duplicate]

1

I'm mapping a 1 x N relationship using a POCO class to use with the Entity Framework 6 . In this case, I have a Cart entity that has multiple Products :

public class Carrinho
{
    //Outras propriedades da classe

    public virtual ICollection<Produto> Produtos { get; set; }  
}

public class Produto
{
    //Propriedades da classe
}

In this scenario, we say that the Products property of the Cart class is a navigation property . Why should it be marked as virtual ?

    
asked by anonymous 15.03.2017 / 13:42

1 answer

2

It turns out that by creating the property as virtual the Entity Framework will create a new class (which is called dynamic proxy ) at runtime and use it instead of using the class original.

This new class, which was created dynamically, contains the code (the logic) needed to load the database entities on the first access to the property. This way, EF does not need to load the entire tree of related objects when it fetches a record. That's what's called Lazy Loading.

    
15.03.2017 / 13:47