我们是否需要在数据库事务失败后显式调用回滚
Do we need to explicitly call Rollback after a failed database transaction
我遇到的大多数实现事务的代码都显式调用回滚。我们需要调用回滚吗?不会自动处理调用回滚吗?明确调用回滚的目的是什么?
谢谢大家
public void DatabaseUpdate ()
{
using var MyTransaction = MyContext.Database.BeginTransaction () ;
if (MethodIsSuccessful ())
{
MyTransaction.Commit () ;
}
else
{
// MyTransaction.Rollback () ; // Not necessary, will be called by Dispose, right ?
}
}
Dispose()
不调用 Rollback()
,它只是清理事务对象并确保 Entity Framework 不再使用该事务。
这就把我们带到了数据库。 Sql Server documentation 表示
Depending on the current transaction isolation level settings, many resources acquired to support the Transact-SQL statements issued by the connection are locked by the transaction until it is completed with either a COMMIT TRANSACTION or ROLLBACK TRANSACTION statement. Transactions left outstanding for long periods of time can prevent other users from accessing these locked resources, and also can prevent log truncation.
所以是的,您确实需要明确地调用 Rollback()
,如果这是您的意图。
我遇到的大多数实现事务的代码都显式调用回滚。我们需要调用回滚吗?不会自动处理调用回滚吗?明确调用回滚的目的是什么?
谢谢大家
public void DatabaseUpdate ()
{
using var MyTransaction = MyContext.Database.BeginTransaction () ;
if (MethodIsSuccessful ())
{
MyTransaction.Commit () ;
}
else
{
// MyTransaction.Rollback () ; // Not necessary, will be called by Dispose, right ?
}
}
Dispose()
不调用 Rollback()
,它只是清理事务对象并确保 Entity Framework 不再使用该事务。
这就把我们带到了数据库。 Sql Server documentation 表示
Depending on the current transaction isolation level settings, many resources acquired to support the Transact-SQL statements issued by the connection are locked by the transaction until it is completed with either a COMMIT TRANSACTION or ROLLBACK TRANSACTION statement. Transactions left outstanding for long periods of time can prevent other users from accessing these locked resources, and also can prevent log truncation.
所以是的,您确实需要明确地调用 Rollback()
,如果这是您的意图。