EntityFramework在一个对象失败时回滚所有事务

时间:2013-03-14 05:00:43

标签: c# entity-framework

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

1 个答案:

答案 0 :(得分:6)

看起来你可以这样做:

_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