I know that there are so many questions about calling a virtual member in the constructor (before marking this as a duplicate). And I already understood why the problem arises.
There are two more unanswered questions for me:
Entity Framework 6 wants me to set foreign collection keys to virtual ones. But I want to initialize them somewhere to prevent NullReferenceExceptions.
Regarding the case study:
public class Student
{
public Student() { }
public int StudentId { get; set; }
public string StudentName { get; set; }
public virtual Standard Standard { get; set; }
}
public class Standard
{
public Standard()
{
Students = new List<Student>();
}
public int StandardId { get; set; }
public string Description { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
They definitely want me to initialize virtual ICollection<Student>in the constructor. What I understood from another Q & As about this topic is only about inheritance. When my class is not inherited, this is normal (not good, but OK).
(ReSharper , . eeehm, , , Entity Framework ? .) .
# 6
public virtual ICollection<Student> Students { get; set; } = new List<Student>();
, , ?
public class Standard
{
public Standard()
{
Students = InitializeMyListAndDoSomethingElse();
}
public virtual ICollection<Student> InitializeMyListAndDoSomethingElse()
{
DoSomethingElse();
return new List<Student>();
}
public virtual ICollection<Student> Students { get; set; };
}