我注意到,默认情况下,Entity Framework Code First 忽略实例化 ICollection<T>
属性,除非集合中至少有一项。我更希望该集合保证始终为空 HashSet
(即 HashSet
具有零项)而不是 null
如果不存在任何项目。
EF Code First 是否有任何约定或设置可以实现这一点?
最佳答案
在实体的构造函数中刚刚设置实例化集合:
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; }
}
抑制消息是针对 FXcop 的。
关于c# - EF Code First 约定允许 ICollection<T> 属性为空集合而不是 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8408570/