Why do navigation properties need to be declared virtual?

Asked

Viewed 39 times

1

I’m mapping a relationship 1 x N using a class POCO (Plain Old CLR Object) to be used with the Entity Framework 6. In this case, I own an entity Cart which has several 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 property Products class Cart is a navigation Property. Why should she be marked as virtual?

  • 1

    I didn’t even realize I already had that question on the website.

  • I don’t either, it’s really duplicated.

1 answer

2


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

This new class, which was created dynamically, contains the code (the logic) needed to load the database entities into the first access to the property. Thus, EF does not need to load the whole related object tree when fetching a record. This is what is called Lazy Loading.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.