首页 > 解决方案 > 回滚时的实体框架 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();
}

错误是:

InvalidOperationExceptionId:实体类型“ ”上的属性“ ”在GenericAttribute尝试将实体的状态更改为“ ”时具有临时值Unchanged。显式设置永久值或确保将数据库配置为为此属性生成值

标签: c#entity-frameworkasp.net-mvc-4

解决方案


当我有唯一索引时,我遇到了同样的异常,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。


推荐阅读