Why are relationships in the Entity Framework code first pointed with Icollection<T>?

Asked

Viewed 226 times

3

Why are relationships in the Entity Framework code first pointed to with Icollection? What is the best instantiation(?) for the property in common cases? List? Using the virtual keyword is only to enable Lazy loading on the property?

1 answer

6

Why relationships in Entity Framework code first are pointed with Icollection?

Because the lazy load of the Entity Framework puts in this property a dynamic proxy, which represents an object that implements ICollection but that actually isn’t quite a collection of anything.

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

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

As follows:

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

Using the virtual keyword is only to enable Lazy loading on the property?

Not. virtual indicates that the object can receive derivatives of the generic class. For example, you declare a Model called Alimento and another call Fruta, and makes Fruta derive Alimento. Thus declaring:

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

Alimentos may also contain class objects Fruta.

Read more about the modifier virtual here.

Browser other questions tagged

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