Database.BeginTransaction()
可以针对单个事务执行多个操作,以便在任何操作失败时可以回滚更改。
using (var context = new PlanetContext())
{
using (var transaction = context.Database.BeginTransaction())
{
try
{
//Lets assume this works
var jupiter = new Planet { Name = "Jupiter" };
context.Planets.Add(jupiter);
context.SaveChanges();
//And then this will throw an exception
var neptune = new Planet { Name = "Neptune" };
context.Planets.Add(neptune);
context.SaveChanges();
//Without this line, no changes will get applied to the database
transaction.Commit();
}
catch (Exception ex)
{
//There is no need to call transaction.Rollback() here as the transaction object
//will go out of scope and disposing will roll back automatically
}
}
}
请注意,显式调用 transaction.Rollback()
可能是开发人员的惯例,因为它使代码更加不言自明。此外,可能有(不太知名的)实体框架的查询提供程序没有正确实现 Dipsose
,这也需要一个明确的 transaction.Rollback()
调用。