首页 > 解决方案 > 调用 DetectChanges() 时,外键属性不会自动更新

问题描述

我有一个非常基本的示例 C# 程序(简化为更复杂的程序),它使用 EF6 和 DbContext 并包含两个类:

Teacher   1...n   Lesson

当移除教师实例时,有一个 FK 约束将课程中的 FK 列设置为空。

示例程序:

using (var context = new EFTestEntities()) {
  // An instance of Teacher (named teacher) and Lesson (named lesson) are created,
  // both are added to the context and context.SaveChanges() is called.

  // teacher is assigned to lesson and DetectChanges() is called.

  using (var context2 = new EFTestEntities()) {
    // Get teacher from the DB, delete it and save the changes.
  }

  // Because here I know that teacher could have been changed or deleted,
  // I refresh it from the database using ObjectContext.Refresh(RefreshMode.StoreWins).
  // But when SaveChanges() is called,
  // an SqlException concerning FK constraint violation is thrown.
}

当我调试时,我看到:

lesson --> teacher (Navigation Property): null (correct)
lesson --> teacher (Foreign Key Property): ID of deleted teacher (incorrect, should be null)

因为课程中的外键属性仍然指向已删除的教师,所以 SqlException 是有道理的。

但是为什么外键属性仍然指向被删除的老师呢?它应该被设置为何nullDetectChanges()被调用。

观察:

标签: c#entity-framework-6dbcontext

解决方案


推荐阅读