gpt4 book ai didi

C# EF6 回滚更改,EntityState.Unchanged 错误

转载 作者:行者123 更新时间:2023-11-30 23:26:02 25 4
gpt4 key购买 nike

// Rollback changes

switch (entry.State)
{
case EntityState.Added:
entry.State = EntityState.Detached;
break;
case EntityState.Modified:
entry.CurrentValues.SetValues(entry.OriginalValues);
entry.State = EntityState.Unchanged;
break;
case EntityState.Deleted:
entry.State = EntityState.Unchanged;
break;
}

此代码在 EF6 SaveChanges() 异常之后使用

我的 scanrio,我插入了一些值并删除了旧值,然后出现异常。由于回滚,我的数据应该被保留,网站应该可以正常工作。但是我在“EntityState.Modified:”扇区的“EntityState.Unchanged”中得到了这个异常

Message=The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted. Source=EntityFramework

为什么我不能将数据库上下文更改回之前的状态?

编辑:

如何删除依赖项?

workReport.sepapayments.Remove(sepaPayment);

workReportAccountSettlement.workreports.Remove(workReport);

最佳答案

而不是从集合中移除实体

workReport.sepapayments.Remove(sepaPayment);

workReportAccountSettlement.workreports.Remove(workReport);

尝试删除它们

myDBContext.Entry(sepaPayment).State = System.Data.Entity.EntityState.Deleted;  

myDBContext.Entry(workReport).State = System.Data.Entity.EntityState.Deleted;

或者你可以

myDBContext.ObjectContext.DeleteObject(sepaPayment);

See also this answer .你得到这个异常的原因是因为 FK 是不可空的,那些实体(类)之间的 UML 关联是一个组合,所以你需要完全删除实体或先更改相关实体的 FK。

关于C# EF6 回滚更改,EntityState.Unchanged 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37045422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com