繁体   English   中英

实体框架代码优先的多对多关系

[英]Entity framework code first many-to-many relationshiop initialization

在下面的Entity Framework官方示例中

  1. 为什么Students的初始化仅存在于Course的构造函数中( this.Students = new HashSet<Student>(); )? 为什么不在Student的构造函数中?
  2. 是否需要初始化? 我曾经实现一对多关系,但是我没有初始化虚拟List<...> ,并且程序运行正常。 (是因为我使用List<...>而不是ICollection<...>吗?

码:

public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    [Required]
    public string StudentName { get; set; }

    public int StdandardId { get; set; }

    public virtual ICollection<Course> Courses { get; set; }
}

public class Course
{
    public Course()
    {
        this.Students = new HashSet<Student>();
    }

    public int CourseId { get; set; }
    public string CourseName { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}
  1. 无需初始化它,因为它被标记为virtual并且将根据需要进行延迟加载。 但是,如果他们尝试将新项目插入Students集合,则此初始化很重要-因为它可以防止NullReferenceException
  2. 你真的应该使用ICollection ,而不是一个List -在99%的情况下ICollection合同是足够的,让你设计出更灵活的使用接口,而不是一类的(例如,你可以使用的HashSet,而不是列表)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM