简体   繁体   中英

Entity Framework InvalidOperationException on rollback

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 .

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();
}

and the Error is :

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

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 :-) )

Code sample (simplified):

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM