I've noticed that, by default, Entity Framework Code First neglects to instantiate ICollection<T> properties unless there is at least one item in the collection. I would much prefer that the collection were guaranteed to always be an empty HashSet (i.e., a HashSet with zero items) rather than null if no items exist.
Is there any convention or setting for EF Code First that would enable this?
in the constructor of the entity just set instantiate the collection:
public sealed partial class EntityClass
{
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",
Justification = "EF 4.1 requires them to be virtual, and RIA Services requires the collections to be instantiated.")]
public EntityClass()
{
OtherEntities = new List<OtherEntity>();
}
public virtual ICollection<OtherEntity> OtherEntities { get; set; }
}
The suppression message is there for FXcop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With