您不需要
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,如果不为null,则回滚事务(如果已提交,则为
_innerConnectionnull)。让我们看看
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); }}


