EF中的HashSet多对多 [英] HashSet in EF many to many

查看:224
本文介绍了EF中的HashSet多对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以EF Code-first来实现多对多.我找到了以下代码:

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; }
    }

除了:

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

您能告诉我为什么这部分是必要的吗?谢谢.

Can you tell me why this part is necessary? Thanks.

推荐答案

这是必需的,因为您必须实例化要使用的ICollection的特定实现. HashSet实现了一个哈希表,该哈希表对于许多操作都非常有效,例如,在大集合中搜索单个项目.但是您可能有理由选择其他实现,例如List.将集合实例化为this.Students = new List<Student>();同样好-Entity Framework无关,但出于效率考虑,默认值为HashSet.

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.

这篇关于EF中的HashSet多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆