简体   繁体   中英

Entity framework code first many-to-many relationshiop initialization

In the following Entity framework official example .

  1. Why the initialization of Students exists in the constructor of Course only ( this.Students = new HashSet<Student>(); )? Why not in the constructor of Student ?
  2. Is the initialization necessary? I used to implement one-to-many relationship and I didn't initial the virtual List<...> and the program works fine. (Is it because I used List<...> instead of ICollection<...> ?

code:

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. There is no need to initialize it, because it is marked as virtual and will be lazy-loaded on demand. However, if they tried to insert new items into the Students collection, this initialization would matter - because it prevents NullReferenceException
  2. You really should use ICollection instead of a List - in 99% cases ICollection contract is enough and using an interface instead of a class makes you design more flexible (for example you can use HashSet and not the List)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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