4

我有这种情况,我即将连续向 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
4

1 回答 1

8

看起来你可以这样做:

_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
于 2013-03-14T05:02:30.680 回答