回滚时的实体框架InvalidOperationException [英] Entity Framework InvalidOperationException on rollback

查看:70
本文介绍了回滚时的实体框架InvalidOperationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Windows应用程序与nopcommerce集成在一起.因此,当我从nopcommerce注册客户时,所有信息都应保存到Windows应用程序的新表 Customer 中.为此,我在表 GenericAttribute 上插入后创建了触发器.

I am integrating my windows application with nopcommerce. So In that when I register the customer from nopcommerce then all the info should be saved to new table Customer of my windows app. for that I created trigger after insert on Table GenericAttribute.

但是当我要注册客户时,在 EfRepository.cs 处的以下架构中会发生错误:

But when I am going to register customer then error occurs in following schema at 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 "时有一个临时值实体的状态为"未更改".明确设置永久值或确保已将数据库配置为为此属性生成值

InvalidOperationException: The property 'Id' on entity type 'GenericAttribute' has a temporary value while attempting to change the entity's state to 'Unchanged'. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property

推荐答案

当我拥有唯一索引时,我遇到了同样的异常,AddRange在唯一索引上失败,然后在catch异常块内尝试删除整个插入的集合.(不是我的代码,但是我必须修复它:-))

I got the same exception when I had unique index, AddRange failed on unique index and then inside the catch exception block was try to remove whole inserted collection. (Not my code, but I had to fix it :-) )

代码示例(简体):

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.

I think that you're trying to do the same thing (internally) different way. Just use transactions instead of hacking EF.

这篇关于回滚时的实体框架InvalidOperationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆