问题
In Entity Framework 4.1 when creating a 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?
回答1:
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.
来源:https://stackoverflow.com/questions/5703761/entity-framework-4-1-code-first-should-many-relationship-icollections-be-initi