0

I have two methods which start sql transaction and commit (or rollback) the connection inside the method.

public void Method1(SqlConnection connection)
{
    var trans = connection.BeginTransaction();
    // do some work
    trans.Commit(); // or trans.Rollback(); 
}

public void Method2(SqlConnection connection)
{
    var trans = connection.BeginTransaction();
    // do some work
    trans.Commit(); // or trans.Rollback(); 
}

I have to create another method which executes logic of Method 1 and 2 but in a single transaction.

public void Method1And2(SqlConnection connection)
{
    var trans = connection.BeginTransaction();
    // do work of method 1
    // do work of method 2
    trans.Commit(); // or trans.Rollback(); 
}

Instead of duplicating code of method 1 and 2 inside Method1And2, I would like to call Method1 and Method2 from Method1And2 but still keeping a single db transaction. Method1 and Method2 will also require their own transaction if they are invoked directly.

What is the best approach to implement this in .Net?

Thanks.

2
  • 1
    What about creating a wrapper that implements IDbConnection like DbConnectionWithNestedTransactionSupport which returns NestableDbTransaction when BeginTransaction is called (the same if called multiple times and the current transaction is pending). The NestableDbTransaction : IDbTransaction would only commit when Commit is called the same number of times as BeginTransaction (would have a reference to the connection) or Rollback. If Rollback is called once then any further Commit calls would be considered as Rollback. Commented Apr 12, 2017 at 1:55
  • Another and perhaps cleaner approach would be to have an application layer that starts the transactions (application use case entry point) and delegate to a business layer which would not handle transactions. Commented Apr 12, 2017 at 1:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.