Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First convention to allow ICollection<T> properties to be empty collections rather than null?

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?

like image 731
devuxer Avatar asked Jan 27 '26 01:01

devuxer


1 Answers

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.

like image 185
Alastair Pitts Avatar answered Jan 28 '26 14:01

Alastair Pitts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!