使用Hashset初始化对象

时间:2015-01-09 09:04:07

标签: list properties entity hashset icollection

我在实体框架的学习曲线中。我按照msdn中的实体框架中的教程进行操作。在样本中,实体定义如下;

public class Department 
{ 
    public Department() 
    { 
        this.Courses = new HashSet<Course>(); 
    } 
    // Primary key 
    public int DepartmentID { get; set; } 
    public string Name { get; set; } 
    public decimal Budget { get; set; } 
    public System.DateTime StartDate { get; set; } 
    public int? Administrator { get; set; } 

    // Navigation property 
    public virtual ICollection<Course> Courses { get; private set; } 
} 

public class Course 
{ 
    public Course() 
    { 
        this.Instructors = new HashSet<Instructor>(); 
    } 
    // Primary key 
    public int CourseID { get; set; } 

    public string Title { get; set; } 
    public int Credits { get; set; } 

    // Foreign key 
    public int DepartmentID { get; set; } 

    // Navigation properties 
    public virtual Department Department { get; set; } 
    public virtual ICollection<Instructor> Instructors { get; private set; } 
} 

public class Instructor 
{ 
    public Instructor() 
    { 
        this.Courses = new List<Course>(); 
    } 

    // Primary key 
    public int InstructorID { get; set; } 
    public string LastName { get; set; } 
    public string FirstName { get; set; } 
    public System.DateTime HireDate { get; set; } 

    // Navigation properties 
    public virtual ICollection<Course> Courses { get; private set; } 
} 

我只展示了一些专注于我的问题的课程。完整样本为here。我怀疑是 为什么在构造函数中使用hashset来创建ICollection属性?

在集合操作中,hashset性能很好如果hashset在这些类型的区域中是合适的,那么

为什么他们在&#39;教练&#39;的构造函数中使用List初始化?实体吗

可以简单地显示2个选项。但如果没有,请建议并告诉我使用hashset的任何其他一般情况。在这里,他们返回ICollection,仅用于初始化他们使用hashset。

1 个答案:

答案 0 :(得分:0)

我相信他们这样做是因为HashSet强制执行唯一性。所以部门的课程必须是独一无二的。但对于教练来说可能并非如此

相关问题