Не е необходимо да се обаждате на Rollback ръчно, защото използвате using изявление.
DbContextTransaction.Dispose методът ще бъде извикан в края на using блок. И автоматично ще отмени транзакцията, ако транзакцията не е успешно ангажирана (не е извикана или се срещат изключения). Следва изходният код на SqlInternalTransaction.Dispose метод (DbContextTransaction.Dispose най-накрая ще му делегира, когато използвате доставчик на SqlServer):
private void Dispose(bool disposing)
{
// ...
if (disposing && this._innerConnection != null)
{
this._disposing = true;
this.Rollback();
}
}
Виждате ли, той проверява дали _innerConnection не е null, ако не, връщане на транзакцията (ако е ангажирана, _innerConnection ще бъде нула). Нека видим какво Commit прави:
internal void Commit()
{
// Ignore many details here...
this._innerConnection.ExecuteTransaction(...);
if (!this.IsZombied && !this._innerConnection.IsYukonOrNewer)
{
// Zombie() method will set _innerConnection to null
this.Zombie();
}
else
{
this.ZombieParent();
}
// Ignore many details here...
}
internal void Zombie()
{
this.ZombieParent();
SqlInternalConnection innerConnection = this._innerConnection;
// Set the _innerConnection to null
this._innerConnection = null;
if (innerConnection != null)
{
innerConnection.DisconnectTransaction(this);
}
}