更新时间:2023-02-13 17:02:14
作为官方文档演示,如果要防止Null引用异常,应始终在实体构造函数内部初始化集合导航属性.
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
}
只有在至少有一个学生的情况下,实体框架才会使用代理填充 Students
属性(否则使用属性)(如果尚未初始化,则为null).
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).
当实体不是代理时,则只有当使用上下文的原始 entity 进行比较时,Entity Framework才在上下文中调用 SaveChanges()
来跟踪其更改.此答案将进一步阐明这种行为.
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.