Entity Framework 4.1 Code First - Should many relationship ICollections be initialised
In Entity Framework 4.1 when creating a开发者_StackOverflow POCO, should the class be coded to initialise the Many relationships or is there some reason to allow 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 a better pattern still?
The first version is correct. It will allow you to initialize collection when you are creating a new entity but in the same time it will allow EF to initialize the collection when it materializes the entity loaded from DB and wrapps it by dynamic proxy for lazy loading.
精彩评论