user2945722
user2945722

Reputation: 1313

How to revert save changes of an entity dbcontext

I need to save multiple tables in my entity context at different times. If one of the save change methods runs but another save change method for a different table fails I am trying to revert the database back to it's original state.

To achieve this I am trying to create two entity contexts, seen below. The first entity I will change and call the SaveChanges method on the different tables when needed. However if an error occurs I am trying to then use the second entity context to overwrite any changes to the database that occurred so far.

Is there a way to overwrite the database values with the "origianlEntityValues" context I created at the start of the program?

Code samples below to hopefully explain it clearer

I instantiate two entity contexts at the start of my program (they inherit from DbContext). One I will make changes to. The other i am trying to use in case an error occurs to revert the changes

SystemEntities entity = new SystemEntities();
SystemEntities originalEntityValues = new SystemEntities();

Throughout the program I need to save tables individually as I need to get their generated Id values and use them in the other entity classes which I then go on to call save changes on, so I call code like this

entity.Contact.SaveChanges();
.... 
entity.Transact.SaveChanges();

If the first save changes runs fine but the second causes an error I am trying to use the "originalEntityValues" to overwrite the previous save changes calls so my database has the same values when the program started in the event of an unexpected error.

catch{  
  // refresh the database with the originalEntityValues context?
}

Any help is much appreciated thanks in advance.

Upvotes: 0

Views: 1087

Answers (1)

magicandre1981
magicandre1981

Reputation: 28826

Have you tried to use the TransactionScope class to wrap this into 1 large transaction? When something went wrong, the data are not written until TransactionScope.Complete is called.

Upvotes: 2

Related Questions