Sqlserver
 SQL >> Base de données >  >> RDS >> Sqlserver

Comprendre l'annulation d'une transaction dans Entity Framework 6

Vous n'avez pas besoin d'appeler vous-même Rollback, car l'instruction using s'en charge pour vous.

La méthode DbContextTransaction.Dispose s'exécute à la fin du bloc using et annule automatiquement la transaction si celle-ci n'a pas été validée avec succès (soit parce que Commit n'a jamais été appelé, soit parce qu'une exception a été levée). Voici le code source de la méthode SqlInternalTransaction.Dispose (DbContextTransaction.Dispose finit par lui déléguer sous le fournisseur SqlServer) :

private void Dispose(bool disposing) { // ... if (disposing && this._innerConnection != null) { this._disposing = true; this.Rollback(); } } 

Comme vous pouvez le constater, elle vérifie si _innerConnection n'est pas null et, le cas échéant, procède à l'annulation (une validation réussie met _innerConnection à null). Regardez maintenant ce que fait 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); } }