【问题标题】:Entity framework, what is the purpose of List<> in construtor:实体框架,构造函数中 List<> 的目的是什么:
【发布时间】:2016-02-04 19:32:24
【问题描述】:
public class Standard
{
    public Standard()
    {
        Students = new List<Student>();
    }
    public int StandardId { get; set; }
    public string Description { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

首先将Students = new List&lt;Student&gt;();构造成EF代码的目的是什么?

【问题讨论】:

    标签: asp.net entity-framework frameworks ef-code-first


    【解决方案1】:

    您当然不必在构造函数中初始化学生。还有其他模式。请注意,完全有可能在不运行构造函数的情况下构造一个对象(例如,一些序列化程序就是这样工作的),所以这甚至可能不适用于所有情况。

    在您初始化学生之前,它将为空。如果您在任何初始化发生之前在代码中的某处尝试Students.Add(myStudent),您将收到 NullReferenceException。

    另一种常见的模式是对 Students 属性执行延迟初始化,例如

    private List<Student> students;
    public List<Student> Students 
    {
        get
        {
            if (students == null) students = new List<Student>();
            return students;
        }
        set { students = value; }
    }
    

    如果一个对象可能在没有运行构造函数的情况下被构造,但也有它自己的一组缺陷(例如,它不是线程安全的),这种模式会很有帮助。

    【讨论】:

    • 我在 EF Models fluent api 示例中看到了这个:entityframeworktutorial.net/code-first/… 就像,值得构建它但不能确定什么?
    • 这是一种非常常见的模式,在大多数情况下都能正常工作。
    • 很明显,这很常见。但究竟是为了什么目的?
    • 如果您不初始化学生,则无法将任何内容添加到您的列表中。尝试注释掉Students = new List&lt;Student&gt;(); 行并试一试。 Students 将为 null,因此当您第一次尝试向 Student 添加内容时(没有对其进行初始化),您将收到 NullReferenceException。实际上,这就像null.Add(myStudent)
    • 但是如果我同意稍后初始化,我还需要将它添加到constr.中吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    相关资源
    最近更新 更多