Entity Framework 6 navigation collections are null instead of empty

前端 未结 1 1449
花落未央
花落未央 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(); // 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.

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