In the following Entity framework official example .
Students
exists in the constructor of Course
only ( this.Students = new HashSet<Student>();
)? Why not in the constructor of Student
? List<...>
and the program works fine. (Is it because I used List<...>
instead of ICollection<...>
? code:
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
and will be lazy-loaded on demand. However, if they tried to insert new items into the Students
collection, this initialization would matter - because it prevents NullReferenceException
ICollection
instead of a List
- in 99% cases ICollection
contract is enough and using an interface instead of a class makes you design more flexible (for example you can use HashSet and not the List)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.