dev*_*xer 3 c# entity-framework code-first ef-code-first entity-framework-4.1
我注意到,默认情况下,Entity Framework Code First忽略了实例化ICollection<T>属性,除非集合中至少有一个项目.我更倾向于保证集合总是空的HashSet(即,HashSet零项目),而不是null没有项目存在.
EF Code First是否有任何约定或设置可以启用此功能?
Ala*_*tts 10
在实体的构造函数中,只需设置实例化集合:
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; }
}
Run Code Online (Sandbox Code Playgroud)
FXcop有抑制消息.