EF 事务

EF 事务

http://yanwushu.byethost7.com/?p=87

1. EF对事务进行了封装:context的saveChange()是有事务性的。

2. 依赖多个不同的Context的操作(即分布式操作)或者多次调用context.saveChanges()操作,会脱离EF事务封装,此时可使用TransactionScope实现事务操作。案例代为:

  1. using (TransactionScope scope = new TransactionScope())  
  2. {  
  3.     //Do something with context1  
  4.     //Do something with context2  
  5.    
  6.     //Save and discard changes  
  7.     context1.SaveChanges();  
  8.    
  9.     //Save and discard changes  
  10.     context2.SaveChanges();  
  11.    
  12.     //if we get here things are looking good.  
  13.     scope.Complete();  
  14. }  

但是这样写是有风险的,假 如context1.SaveChanges()成功了,context2.SaveChanges()失败,在scope.Complete()提交事务的时候就会终止,而Context1已经成功执行了这可能不一定符合的需要。如果需要 context1、context2要不同时执行成功,要不都不成功,需要对代码作小小的调整,如用下面的代码: 

  1. using (TransactionScope scope = new TransactionScope())  
  2. {  
  3.     //Do something with context1  
  4.     //Do something with context2  
  5.    
  6.     //Save Changes but don't discard yet  
  7.     context1.SaveChanges(false);  
  8.    
  9.     //Save Changes but don't discard yet  
  10.     context2.SaveChanges(false);  
  11.    
  12.     //if we get here things are looking good.  
  13.     scope.Complete();  
  14.     context1.AcceptAllChanges();  
  15.     context2.AcceptAllChanges();  
  16.    
  17. }  

用SaveChanges(false)先将必要的数据库操作命令发送给数据库,这是注意context1与context2并没有真正发生改变,如果事务终止,自动回滚,两者的更改都没有真正提交到数据库,所以是可以成功回滚的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值