C# 实体框架代码第一个多对多关系操作初始化
在下文中C# 实体框架代码第一个多对多关系操作初始化,c#,entity-framework,ef-code-first,entity-framework-6,C#,Entity Framework,Ef Code First,Entity Framework 6,在下文中 为什么学生的初始化只存在于课程的构造函数中(this.Students=new HashSet();)?为什么不在学生的构造函数中 是否需要初始化?我曾经实现一对多关系,我没有初始化虚拟的列表,程序运行良好。(是因为我使用了列表而不是ICollection 代码: public class Student { public Student() { } public int StudentId { get; set; } [Required] publi
学生的初始化只存在于课程的构造函数中(this.Students=new HashSet();
)?为什么不在学生的构造函数中李>
是否需要初始化?我曾经实现一对多关系,我没有初始化虚拟的列表
,程序运行良好。(是因为我使用了列表
而不是ICollection
代码:
public class Student
{
public Student() { }
public int StudentId { get; set; }
[Required]
public string StudentName { get; set; }
public int StdandardId { 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; }
}
公共班级学生
{
公立学生(){}
公共int StudentId{get;set;}
[必需]
公共字符串StudentName{get;set;}
公共int StdandardId{get;set;}
公共虚拟ICollection课程{get;set;}
}
公共课
{
公共课程()
{
this.Students=newhashset();
}
public int CourseId{get;set;}
公共字符串CourseName{get;set;}
公共虚拟ICollection学生{get;set;}
}
无需对其进行初始化,因为它被标记为virtual
,并且将根据需要延迟加载。但是,如果他们试图将新项目插入Students
集合,则此初始化将很重要,因为它可防止NullReferenceException
您确实应该使用ICollection
而不是List
——在99%的情况下ICollection
契约就足够了,使用接口而不是类可以使您的设计更加灵活(例如,您可以使用HashSet而不是List)