简体   繁体   中英

Do I need to manually roll back a transaction if not committing changes given some conditions?

Example: Using transaction, and only committing if a given condition is satisfied.

using (var transaction = context.Database.BeginTransaction())
    // ...
    if (modelState.IsValid) {
        transaction.Commit();
    }
}

does it need to be:

using (var transaction = context.Database.BeginTransaction())
    // ...
    if (modelState.IsValid) {
        transaction.Commit();
    } else {
        transaction.Rollback();
    }
}

or there is no need for the else part. What happens if I don't specify? Any good guidelines?

You don't need to call Rollback manually because you are using the using statement. It is not necessary to explicitly call Rollback . The transaction will be rolled-back if Commit() has not been called.

DbContextTransaction.Dispose method will be called in the end of the using block. And it will automatically rollback the transaction if the transaction is not successfully committed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM