HashSet in EF many to many

*爱你&永不变心* 提交于 2019-12-11 12:49:46

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/28691089/hashset-in-ef-many-to-many

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!