c# - 回滚时的实体框架 InvalidOperationException
问题描述
我正在将我的 Windows 应用程序与 nopcommerce 集成。因此,当我从 nopcommerce 注册客户时,所有信息都应保存到Customer
我的 windows 应用程序的新表中。为此,我在 Table 上插入后创建了触发器GenericAttribute
。
但是当我要注册客户时,以下架构中会出现错误EfRepository.cs
:
protected string GetFullErrorTextAndRollbackEntityChanges(DbUpdateException exception)
{
//rollback entity changes
if (_context is DbContext dbContext)
{
var entries = dbContext.ChangeTracker.Entries()
.Where(e => e.State == EntityState.Added || e.State == EntityState.Modified).ToList();
entries.ForEach(entry => entry.State = EntityState.Unchanged); //here error occurs
}
_context.SaveChanges();
return exception.ToString();
}
错误是:
InvalidOperationException
Id
:实体类型“ ”上的属性“ ”在GenericAttribute
尝试将实体的状态更改为“ ”时具有临时值Unchanged
。显式设置永久值或确保将数据库配置为为此属性生成值
解决方案
当我有唯一索引时,我遇到了同样的异常,AddRange 在唯一索引上失败,然后在 catch 异常块内尝试删除整个插入的集合。(不是我的代码,但我必须修复它:-))
代码示例(简化):
try {
context.AddRange(users); // List<User>, has property List<Contact>
context.SaveChanges(); // throws exception on unique index
} catch (Exception ex) {
context.RemoveRange(users); // this throws exception "The property 'UserID' on entity type 'Contact' has a temporary value"
throw;
}
我认为您正在尝试以不同的方式(内部)做同样的事情。只需使用事务而不是破解 EF。
推荐阅读
- odata - ODataLib 7.5 中的 UnBoundFunctionPathSegment 在哪里?
- mongodb - 启动 mongod 服务的 Ansible 任务永远挂起
- jquery - jQuery AJAX + ASMX - 开发上的内部服务器错误但不是本地的
- c# - 无需使用托管在 C# WebApi 中的 ngrok 即可用于生产的 Slack 应用程序
- r - Shiny - 基于复选框的聚合条形图
- visual-studio - 没有自定义 ChromeWindow 的 XAML 设计器预览
- angular - 在角度 6 中单击另一个按钮后,可观察到的为空
- apache-spark - 向火花数据框添加新列
- reactjs - Create-React-App 中的启动画面
- delphi - FreeAndNil 程序是否也释放线程中创建的 TStringList?