Doubt with EntityFramework CodeFirst

5

I'm starting in the Entity Framework and am having a question regarding CodeFirst . Why do 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;}
}
    
asked by anonymous 11.08.2015 / 23:25

1 answer

9

For two reasons:

  • Why is the Entity Framework that mounts this object for you;
  • Because it is not necessarily a list or a collection. It can be a Dynamic Proxy, which does the Framework lazy loading procedure. I explain this here #
  • This is incorrect:

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

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

    The correct one is:

    public virtual ICollection<Produto> Produtos { get; set; }
    
        
    11.08.2015 / 23:30