在自定义工作单元中可能有多个 DbContext 的情况下,EF5 是否会管理所有事务要求,或者下面的代码是否仍然有效/需要?如果没有,代码可以减少多远并且仍然提供相同的功能?
public void SaveAllChanges()
{
var transactions = new List<DbTransaction>();
foreach (var context in this.contexts
.Where(context => context != null)
.Select(dbcontext => ((IObjectContextAdapter)dbcontext).ObjectContext))
{
context.Connection.Open();
var databaseTransaction = context.Connection.BeginTransaction();
transactions.Add(databaseTransaction);
try
{
context.SaveChanges();
}
catch
{
foreach (var transaction in transactions)
{
try
{
transaction.Rollback();
}
finally
{
databaseTransaction.Dispose();
}
}
transactions.Clear();
throw;
}
}
try
{
foreach (var transaction in transactions)
{
transaction.Commit();
}
}
finally
{
foreach (var transaction in transactions)
{
transaction.Dispose();
}
transactions.Clear();
foreach (var context in this.contexts
.Select(dbcontext => ((IObjectContextAdapter)dbcontext).ObjectContext)
.Where(context => context.Connection.State != ConnectionState.Closed))
{
context.Connection.Close();
}
}
}
假设 SQL Server 2008 及更高版本。