Entity Framework 4.1 Code First - many ICollections relationships need to be initialized

In Entity Framework 4.1, when creating POCO, if the class needs to be encoded to initialize Many relationships, or is there some reason that allows the Entity Framework to have control over these properties?

public class Portfolio { private ICollection<Visit> _visits; public virtual ICollection<Visit> Visits { get { if (_visits == null) { _visits = new List<Visit>(); } return _visits; } set { _visits = value; } } } 

or

 public class Portfolio { public virtual ICollection<Visit> Visits { get; set; } } 

Is there an even better template?

+4
c # ef-code-first
source share
1 answer

The first version is correct. This will allow you to initialize the collection when creating a new object, but at the same time, it will allow EF to initialize the collection when it materializes the object loaded from the database and wraps it with a dynamic proxy for lazy loading.

+5
source share

All Articles