I\'m trying to write a relational database application using Entity Framework 6. I have classes analogous to:
public class Subject
{
public int ID { get; set
As the official documentation demonstrates, you should always initialize your collection navigation properties inside the entity constructor if you want to prevent a Null reference exception.
public Subject()
{
Students = new HashSet(); // you may also use List, but HashSet will guarantee that you are not adding the same Student mistakenly twice
}
Entity framework will fill Students
property (using a proxy) only if there is at least a student, else it will leave the property as is (null if you have not initialized it).
When the entity is not a proxy, then Entity Framework tracks its changes only when calling SaveChanges()
on the context, using its original entity state for comparison. This answer will further clarify this behavior.