2015-02-24 82 views
1

我試圖在EF Code-first中實現多對多。我發現這個代碼:EF中的HashSet多對多

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

你能告訴我,爲什麼這部分是必要的嗎?謝謝。

回答

1

這是必要的,因爲您必須實例化您想要使用的ICollection的特定實現。 HashSet實現了一個對於很多操作非常有效的散列表,例如爲一個項目搜索一個大集合。但是您可能有選擇其他實現的原因,如List。將收集實例化爲this.Students = new List<Student>();同樣很好 - 實體框架不關心,但出於效率原因,默認值爲HashSet