views:

73

answers:

2

I have a method that A) inserts a row in a table and then B) uses the resulting Identity value in several inserts in another table. If the logic in part B fails for any reason, I need to rollback all of the inserts for both parts B and A. I'm fairly certain that transactions would not work for this, although I'm open to being persuaded otherwise. I have a "main" method that handles the calling to the methods that perform both A and B, which are surrounded by a try-catch. What I'm wondering is, if I call a method that performs rollback functionality from the main method's catch, and something fails in the rollback method, will the exception caught (I want to log it) in the rollback method wipe out the stack trace (or anything else) of the exception caught in the main method? Code example:

public class DoSomeStuff
{
    public void MainMethod(...)
    {
         int identity;
         try
         {
              identity = DoFirstInsert(...);
              DoSubsequentInserts(identity, ....);
         }
         catch
         {
              RollbackStuff(identity);
              throw;
         }
    }

    void RollbackStuff(int identity)
    {
         try
         {
              //Do database stuff to rollback inserts
         }
         catch(exception ex)
         {
              //Log rollback error, DO NOT THROW
              //Will this wipe out the exception caught in MainMethod()?
         }
    }
}

Thanks in advance.

+3  A: 

Transactions should work. Wrap all of the inserts in a single transaction, including the one that returns the identity column.

John Saunders
+1  A: 
Malcolm
Although this answers your question about exceptions, John Saunder's answer about Transactions is definitely the best way to go to manage rollbacks.
Malcolm