我正试图在EF代码中实现许多-优先。我找到了这个密码:
 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; }
    }我什么都懂,除了:
    public Course()
    {
        this.Students = new HashSet<Student>();
    }你能告诉我为什么需要这部分吗?谢谢。
发布于 2015-02-24 11:15:17
这是必要的,因为您必须实例化您想要使用的ICollection的特定实现。HashSet实现了一个对许多操作非常有效的哈希表,例如,在一个大集合中搜索单个项。但是您可能有选择其他实现的理由,比如List。实例化集合也同样好,因为this.Students = new List<Student>(); - Entity并不在意,但是出于效率原因,默认的是HashSet。
https://stackoverflow.com/questions/28691089
复制相似问题