Search code examples
c#rollbacktransactionscope

multiple TransactionScopes in in different classes C#


Good day, I have a method which contains several database commits (about 15) in a different classes, I need a way to make all the db changes only if the the method did not throw any exception, I am thinking about using a Transaction Scope, and my question is weather i can use a single instance of that Transaction Scope in all the different classes and if not what is the best practice to perform a rollback in case of an exception? Thanks!


Solution

  • You usually don't need to perform rollback explicitly, methods that perform database operations might not even be aware of ambient transaction (that is - you don't need to pass TransactionScope to them). Just do:

    using (var tran = new TransactionScope()) {
        FirstDatabaseOperation();
        SecondDatabaseOperation();
        // etc
        tran.Complete();
    }
    

    If exception happens in any operation - transaction will be rolled back for you, because TransactionScope will be disposed.