Doubt with Codefirst Entityframework

Asked

Viewed 206 times

5

I’m starting in Entity Framework and I have a question regarding Codefirst. Why I have to use as virtual some properties like the example below?

[Table("Grupo")]
public class Grupo
{
   public int ID { get; set; }
   [Required(ErrorMessage="Nome não pode ser branco.")]
   public string Nome { get; set; }

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

1 answer

9


For two reasons:

  1. Because it is the Entity Framework that assembles this object for you;
  2. Because it is not necessarily a list or a collection. It can be a Dynamic Proxy, which makes the lazy loading procedure of the Framework. I explain it here and also here

This is incorrect:

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

IQueryable<> is an object that can evaluate a list, not an actual list. This is explained in more detail here.

The correct is:

public virtual ICollection<Produto> Produtos { get; set; }
  • Good evening Cigado, excuse my ignorance. I did not understand the meaning of what would be a Dynamic Proxy. And on the virtual, you mean then that he is not responsible for making the association between the entities, ie the classes? Another question, always have to be used the Icollection interface or can be used also Ienumerable? Thanks!

  • Dynamic proxy is a class that pretends to be another. In the case of lazy load, instead of a list of Products being loaded, it is placed at the initialization of a Grupo a Dynamic Proxy that pretends to be a list of Products. These Products will only be loaded effectively when you call up this list in some way (in ASP.NET MVC, it’s usually at View). Then the EF carries the Products from the bank to you.

  • About being ICollection or IEnumerable, even works for IEnumerable, but ICollection has some more features, being a more comprehensive interface. Hence my recommendation.

  • @Kellysoares I recommend you ask another question and mark this as accepted, if she solved your question.

Browser other questions tagged

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