I'm trying to implement many to many in EF Code-first. I have found this code :
public class Student
{
public Student() { }
public int StudentId { get; set; }
[Required]
public string StudentName { 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; }
}
I understand everything except :
public Course()
{
this.Students = new HashSet<Student>();
}
Can you tell me why this part is necessary? Thanks.
It's necessary because you have to instantiate the particular implementation of ICollection
that you would like to use. HashSet
implements a hash table that is very efficient for a lot of operations, for instance searching a large set for a single item. But you might have reasons for choosing some other implementation, like List
. It is equally fine to instantiate the collection as this.Students = new List<Student>();
- Entity Framework doesn't care, but the default is HashSet
for efficiency reasons.