c# - 调用 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 是有道理的。
但是为什么外键属性仍然指向被删除的老师呢?它应该被设置为何null
时DetectChanges()
被调用。
观察:
- 不手动调用
Refresh()
导航属性并将其设置为 null:外键按预期更新。所以这个Refresh()
电话一定和这个问题有关。 - 调用
Reload()
ofDbEntityEntry
而不是Refresh()
导致ObjectContext
同样的问题。 - 不仅刷新老师,还刷新课程:使
DetectChanges()
外键按预期更新。但是这样一来,已经对课程所做的所有更改都将丢失。
解决方案
推荐阅读
- linux - 为什么我的 iptables 防火墙会阻止除 Google 网站之外的所有网站?
- r - 'train' 和 'class' 有不同的长度 RStudio
- azure - 如何根据电子邮件地址检查用户是否存在于 B2C 租户中?
- python - 将具有两个不同级别的数据的数据框转换为嵌套字典
- python - 使用 beautifulsoup 抓取房地产经纪人数据
- git - Gitlab部署密钥已配置但仍不授予访问权限
- mongodb - Mongo 反应式存储库和聚合不过滤结果
- java - 从 JTextField 返回字符串的 Java 方法
- python - 如何从 beautifulsoup 结果中切出所需的链接
- python - 根据第一个元素组合嵌套列表