我正在使用 Visual Studio 自动构建 NorthWind 数据库的代码优先模型。我有一些问题。
我发现如果实体类有一个集合,那么这个集合总是在默认构造函数中实例化。为什么我们需要这样做?
ICollection<T>
被实例化为HashSet<T>
在默认构造函数中。为什么是HashSet<T>
用过的?我可以使用List<T>
还是别的?为什么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/