ef中的事务分为两种,隐式事务和显式事务,
context.SaveChanges();
这里ef会创建一个隐式的事务,在context.SaveChanges();后,会自动调用commit命令,这是因为EF本身的操作是具有事务机制的
{
//Do something with context1
context1.SaveChanges(false);
//Do something with context2
context2.SaveChanges(false);
//if we get here things are looking good.
scope.Complete();
context1.AcceptAllChanges();
context2.AcceptAllChanges();
}
使用显示事务,可以对多次数据库连接保持事务一致性,context.SaveChanges(false);告诉ef挂起操作,并没有真正的执行,scope.Complete();真正提交,提交失败,ef会自动回滚
隐式事务(一个上下文):
//do something with contextcontext.SaveChanges();
这里ef会创建一个隐式的事务,在context.SaveChanges();后,会自动调用commit命令,这是因为EF本身的操作是具有事务机制的
显示事务(多个上下文):
using (TransactionScope scope = new TransactionScope()){
//Do something with context1
context1.SaveChanges(false);
//Do something with context2
context2.SaveChanges(false);
//if we get here things are looking good.
scope.Complete();
context1.AcceptAllChanges();
context2.AcceptAllChanges();
}
使用显示事务,可以对多次数据库连接保持事务一致性,context.SaveChanges(false);告诉ef挂起操作,并没有真正的执行,scope.Complete();真正提交,提交失败,ef会自动回滚