Du behöver inte ringa Rollback manuellt eftersom du använder using påstående.
DbContextTransaction.Dispose metod kommer att anropas i slutet av using blockera. Och det kommer automatiskt att återställa transaktionen om transaktionen inte genomförs framgångsrikt (inte anropade eller påträffade undantag). Följande är källkoden för SqlInternalTransaction.Dispose metod (DbContextTransaction.Dispose kommer slutligen att delegera till det när du använder SqlServer-leverantören):
private void Dispose(bool disposing)
{
// ...
if (disposing && this._innerConnection != null)
{
this._disposing = true;
this.Rollback();
}
}
Du förstår, den kontrollerar om _innerConnection är inte null, om inte, återställ transaktionen (om den är genomförd, _innerConnection kommer att vara null). Låt oss se vad Commit gör:
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);
}
}