EntityFramework Rollback All Transactions if One Object Fails

c#, entity-framework

Solution

It seems like you could just do this:

_dbContext.Table1.AddObject(object1);
_dbContext.Table2.AddObject(object2);
_dbContext.Table3.AddObject(object3);
_dbContext.Table4.AddObject(object4);
_dbContext.Table5.AddObject(object5);
_dbContext.SaveChanges(); // if fails will roll back all objects

Problem

I have this scenario that I'm about to add records to 5 or more tables consecutively. The saving mechanism should be strict that any object fails all database changes will not be committed or be rolled back. If all objects were inserted without issue that's the time that all records should be saved to database. Bellow is my sample code. Please help. ``` _dbContext.Table1.AddObject(object1);//if insert fails rollback _dbContext.SaveChanges(); _dbContext.Table2.AddObject(object2);//if insert fails rollback this and object1 transactions _dbContext.SaveChanges(); _dbContext.Table3.AddObject(object3);//if insert fails rollback this and previous other transactions _dbContext.SaveChanges(); _dbContext.Table4.AddObject(object4);//if insert fails rollback this and previous other transactions _dbContext.SaveChanges(); _dbContext.Table5.AddObject(object5);//if insert fails rollback this and previous other transactions _dbContext.SaveChanges(); //if all objects were inserted without exceptions then commit all changes ```

Original source