Entity Framework 6 navigation collections are null instead of empty

前端 未结 1 1462
花落未央
花落未央 2021-02-20 12:57

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         


        
相关标签:
1条回答
  • 2021-02-20 13:05

    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<Student>(); // you may also use List<Student>, 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.

    0 讨论(0)
提交回复
热议问题