Entity Framework中DbContext结合TransactionScope提交事务的正确方式

时间:2023-11-21 22:32:56

问:


I would like know what is the best possible way to implement transactions with DBContext. In particular,

  1. Does DbContext.SaveChanges implement transaction internall if i change multiple entities?
  2. If i want to call DbContext.SaveChanges multiple times(same contxet/different contxets), how transaction can be achieved?

答:


  1. Yes. SaveChanges uses transaction internally.(也就是说SaveChanges方法默认会在内部自己开启一个事务,所有用SaveChanges方法提交到数据库的SQL语句都在同一个数据库事务中)
  2. Use TransactionScope to wrap multiple calls to SaveChanges

Example:

using(var scope = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
{
// Do something
context.SaveChanges();
// Do something else
context.SaveChanges(); scope.Complete();
}

从上面的代码我们可以看出来在Entity Framework中,DbContext(即上面的context变量)上所有实体数据的更改都会在DbContext.SaveChanges方法被调用时提交到数据库,也就是DbContext.SaveChanges方法被调用时,内部会打开一个数据库连接来在数据库上执行相关的SQL语句,然后关闭该数据库连接。由于上面代码中两次DbContext.SaveChanges方法的调用都在一个TransactionScope的using代码块内,所以这两次SaveChanges方法调用开启的数据库连接都在同一个数据库事务下,保证了两次SaveChanges方法执行的SQL语句都在同一个数据库事务下被提交。

原文链接