EntityFramework Rollback all transactions if one object does not work

I have such a scenario that I am going to add records to 5 or more tables sequentially. The storage mechanism must be strict so that any object fails, all changes to the database will not be committed or rolled back. If all objects were inserted without problems, then the time when all records should be stored in the 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 
+4
source share
1 answer

It seems 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 
+6
source

Source: https://habr.com/ru/post/1469138/


All Articles