实体框架:更新不可为空的外键值时出现参照完整性约束冲突错误

问题描述

我们正在使用带有工作单元的Entity Framework和通用存储库模式,以下是该场景中的实体。

@Id

当我们尝试更新具有一对一关系的public class Plan { public Guid PlanUuid { get; set; } // Primary key public virtual ICollection<PlanDetail> Details { get; set; } // has navigation property in edmx } public class PlanDetail { public Guid PlanDetailUuid { get; set; } // Primary Key public virtual Plan Plan { get; set; } // has navigation property in edmx public Guid PlanUuid { get; set; } public virtual Tier Tier { get; set; } // has navigation property in edmx public Guid TierUuid { get; set; } public virtual DevMetrics Metrics { get; set; } // also has navigation property in edmx public Guid MetricUuid { get; set; } } public partial class Tier { public System.Guid TierUuid { get; set; } } 的不可为空的外键(TierUuid)时,出现以下错误

发生了引用完整性约束冲突:当从属对象为Unchanged时,不能更改作为引用完整性约束一部分的主键属性,除非将其设置为关联的主对象。必须跟踪主要对象,并且不将其标记为删除

这是使用的代码:

PlanDetail

以上代码在更新其他public ServiceResponse UpdatePlanDetail(PlanDetailUpdateDTO planDetailUpdateDTO) { //get the plan detail from database based on Id var planDetail = this._unitOfWork.PlanDetailRepository.LoadOnUuid(planDetailUpdateDTO.PlanDetailUuid); // get the new Tier to be applied var tier = this._unitOfWork.TierRepository.LoadOnUuid(planDetailUpdateDTO.tieruuid); //Assign planDetail.Tier = tier; planDetail.TierUuid = tieruuid; //Update this._unitOfWork.PlanDetailRepository.Update(details); // save and log the changes (Audit) this._unitOfWork.SaveAndLogChanges(); } // generic repository update method public virtual void Update(TEntity entityToUpdate) { this._dbSet.Attach(entityToUpdate); this._context.Entry(entityToUpdate).State = EntityState.Modified; } public void SaveAndLogChanges() { // following statement gives the integrity constraint error mentioned above context.ChangeTracker.DetectChanges(); // some other code this._context.SaveChanges(); } 外键(例如Plandetail)时可以完美地工作,但仅在MetricUuid更新时失败。我认为是因为另一个外键(Tieruuid)可为空,所以即使相关对象(MetricUuid)可为空,也可以成功将其保存在数据库中。

我试图在StackOverflow上进行搜索,并在以下语句之前找到了创建新上下文的潜在解决方案,但我不确定这在我的项目中是否可行

DevMetrics

请指导其他解决方案。

谢谢, 阿莫尔

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...