EF中的事务处理的初步理解


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


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

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


 

using (TransactionScope scope = new TransactionScope())
{
    //Do something with context1
    //Do something with context2
 
    //Save and discard changes
    context1.SaveChanges();
 
    //Save and discard changes
    context2.SaveChanges();
 
    //if we get here things are looking good.
    scope.Complete();
}



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


 

using (TransactionScope scope = new TransactionScope())
{
    //Do something with context1
    //Do something with context2
 
    //Save Changes but don't discard yet
    context1.SaveChanges(false);
 
    //Save Changes but don't discard yet
    context2.SaveChanges(false);
 
    //if we get here things are looking good.
    scope.Complete();
    context1.AcceptAllChanges();
    context2.AcceptAllChanges();
 
}



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


transactionScope的理解:


1.不只是用在数据库的事务中,也可以管理别的类型的事务,功能很强大,性能较差

2.应该尽量使用同一个context进行数据库的操作,原因:

节省资源,没创建一个context都是耗费资源的操作。

不同dal中使用同一个context同样可以达到事务处理的目的,所以在一般的数据库事务处理中transactionScope不是必要的


资源


http://www.cnblogs.com/aisini/archive/2011/03/25/1994487.html


 

 

原文地址:https://www.cnblogs.com/riskyer/p/3281237.html