[英]Entity framework code first many-to-many relationshiop initialization
在下面的Entity Framework官方示例中 。
Students
的初始化仅存在于Course
的构造函数中( this.Students = new HashSet<Student>();
)? 为什么不在Student
的构造函数中? List<...>
,并且程序运行正常。 (是因为我使用List<...>
而不是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; }
}
virtual
并且将根据需要进行延迟加载。 但是,如果他们尝试将新项目插入Students
集合,则此初始化很重要-因为它可以防止NullReferenceException
ICollection
,而不是一个List
-在99%的情况下ICollection
合同是足够的,让你设计出更灵活的使用接口,而不是一类的(例如,你可以使用的HashSet,而不是列表)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.