实体框架:为什么实体类的集合类型需要在默认构造函数中实例化? [英] Entity Framework:Why the collection type of entity class need to be instanced in the default constructor?

查看:514
本文介绍了实体框架:为什么实体类的集合类型需要在默认构造函数中实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Visual Studio to build a code first model of NorthWind database automatically. I have some questions.


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

  1. 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?

ICollection< T> 被实例化为$ $ c> HashSet< T> 在默认构造函数中。为什么使用 HashSet< T> ?我可以使用列表< T> 或其他东西?

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

为什么导航属性为一个侧(一对多关系)是 ICollection< T> virtual

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

要按照我上面提到的方式实现实体类,我认为必须有一些好处可以带来。你能告诉我为什么吗?

To Implement the entity class in the way I mention above, I think there must be some benefits can be brought. Can you tell me why?

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?

你没有。在开始向其添加内容之前,它只需要被实例化。

You don't. It just needs to be instantiated before you start adding stuff to it.


ICollection在默认构造函数中被实例化为HashSet。为什么使用HashSet?我可以使用列表或其他东西吗?

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

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

You can use anything that implements ICollection<T> as the concrete implementation.


为什么导航属性在一一侧(一对多关系)是ICollection和虚拟?

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

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

ICollection<T> is the interface that EF expects for navigation properties. It provides the minimal interface necessary to represent that type of relationship. It is virtual so that EF can insert a proxy at runtime to detect changes to the property. If you decide not to make it virtual, you will need to manually inform EF about changes to the property.

这篇关于实体框架:为什么实体类的集合类型需要在默认构造函数中实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆