/// <summary> /// Rollback of entity changes and return full error message /// </summary> /// <param name="exception">Exception</param> /// <returns>Error message</returns> 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 => { try { entry.State = EntityState.Unchanged; } catch (InvalidOperationException) { // ignored } }); } try { _context.SaveChanges(); return(exception.ToString()); } catch (Exception ex) { //if after the rollback of changes the context is still not saving, //return the full text of the exception that occurred when saving return(ex.ToString()); } }