2013-03-14 37 views
4

我有这种情况,即将连续向5个或更多表添加记录。保存机制应该是严格的,任何对象都会失败,所有的数据库更改都不会被提交或回滚。如果插入所有对象都没有问题,那么所有记录都应该保存到数据库中。贝娄是我的示例代码。请帮忙。如果一个对象发生故障,EntityFramework将回滚所有事务

_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

呼叫'的SaveChanges()'在一端时间,EF封装所有事务范围内,但不直接相关的EF像操作I/O操作。 – JOBG 2013-03-14 05:18:03

回答

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 
+1

令人惊叹!我认为实现很复杂。谢谢 – 2013-03-14 06:01:56

相关问题