c# - EF Code First 约定允许 ICollection<T> 属性为空集合而不是 null?

标签 c# entity-framework entity-framework-4.1 ef-code-first code-first

我注意到,默认情况下,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/

相关文章:

c# - 如何使用继承/多态性将 JSON 字符串解析为 C# 对象?

c# - OData 只读属性

c# - 如何将子类属性映射到每个层次结构的表中的列?

asp.net-mvc-3 - 使用数据库的 MVC3 操作过滤器(EF 4.1 DBContext、Ninject)

C# 反射 : How to get the type of a Nullable<int>?

c# - 安全地验证客户端到服务器

c# - 使用 @@TRANCOUNT 有用吗?

C# Datetime 插入 SQL Server 值,精确到微秒

c# - Entity Framework 设置 ID 不应该的时候

c# - 我可以在 EF 中以良好的方式获取列表吗