Why are relations in the Entity Framework code first pointed to with ICollectionT?

3

Why relationships in the Entity Framework code first are pointed to with ICollection? What is the best instantiation (?) For the property in common cases? List Is the use of the virtual keyword only to enable lazy loading on the property?

    
asked by anonymous 06.01.2015 / 21:51

1 answer

6

Why relationships in the Entity Framework code first are pointed to with ICollection?

Because the lazy load of the Entity Framework places this property on a dynamic proxy, it represents an object that implements ICollection but which is not really a collection of anything at all.

When accessing this property, the dynamic proxy is replaced by a true collection (usually List<> ).

What is the best instantiation (?) for the property in common cases?

As follows:

public virtual ICollection<Objeto> Objetos { get; set; }

Is the use of the virtual keyword only to enable lazy loading on the property?

No. virtual indicates that the object can receive derivatives of the generic class. For example, you declare a Model named Alimento and another named Fruta , and causes Fruta to derive Alimento . Declaring this way:

public virtual ICollection<Alimento> Alimentos { get; set; }

Alimentos can also contain objects of class Fruta .

Read more about the virtual modifier here .

    
07.01.2015 / 08:29