c# – EF Code First允许ICollection属性为空集合而不是null的约定?
作者:互联网
我注意到,默认情况下,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,entity-framework,entity-framework-4-1,ef-code-first,code-first 来源: https://codeday.me/bug/20190721/1494692.html