c# - Entity Framework :Why the collection type of entity class need to be instanced in the default constructor?

标签 c# entity-framework code-first

我正在使用 Visual Studio 自动构建 NorthWind 数据库的代码优先模型。我有一些问题。

  1. 我发现如果实体类有一个集合,那么这个集合总是在默认构造函数中实例化。为什么我们需要这样做?

  2. ICollection<T>被实例化为 HashSet<T>在默认构造函数中。为什么是HashSet<T>用过的?我可以使用 List<T>还是别的?

  3. 为什么one 端(一对多关系)的导航属性是ICollection<T>virtual ?

按照我上面说的方式来实现实体类,我想肯定是可以带来一些好处的。你能告诉我为什么吗?

public partial class Orders
{
    public Orders()
    {
        Order_Details = new HashSet<Order_Details>();
    }
    public virtual ICollection<Order_Details> Order_Details { get; set; }
}

最佳答案

I found that if the entity class has a collection, then the is collection always instantiated in the default constructor. Why we need to do that?

你不知道。它只需要在你开始向它添加东西之前实例化。

The ICollection is instantiated as a HashSet in the default constructor. Why is HashSet used? Can i use List or something else?

您可以使用任何实现 ICollection<T> 的东西作为具体实现。

Why is the navigation property at "one" side (one to many relation) is ICollection and virtual?

ICollection<T>是 EF 期望的导航属性接口(interface)。它提供了表示该类型关系所需的最小接口(interface)。它是虚拟的,因此 EF 可以在运行时插入代理来检测属性的更改。如果您决定不将其设为虚拟,您将需要手动通知 EF 有关属性的更改。

关于c# - Entity Framework :Why the collection type of entity class need to be instanced in the default constructor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29873671/

相关文章:

c# - 刷新 WPF 中的 EF 数据绑定(bind)

entity-framework - 联接表中的代码优先Fluent API和导航属性

c# - 防止用户在 Multi-Tenancy 环境中多次投票的最佳方法

c# - Azure 更新计划作业 API - 格式错误的作业对象

entity-framework - 如何在 Entity Framework 4.4 中实现 DBSet.AddOrUpdate?

code-first - 如何在 Entity Framework 4.3.1 中禁用迁移?

c# - 将 2 个表映射到 Entity Framework 中的单个实体

c# - 如果使用设置,Moq 模拟调用将返回 null

c# - 序列化列表<string>时如何选择内部xml标签?

asp.net-mvc - EF 4.1 代码优先 : "non-null value of type ' DateTime'"Issue