我有这样的场景,我要连续向 5 个或更多表添加记录。保存机制应该是严格的,任何对象失败,所有数据库更改都不会提交或回滚。如果所有对象都没有问题地插入,那么所有记录都应该保存到数据库中。下面是我的示例代码。请帮忙。
_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
最佳答案
看起来你可以这样做:
_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
关于c# - 如果一个对象失败,EntityFramework 回滚所有事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15401531/