TransactionScope commits even tho exception was thrown

I have the following very simple block of code:

using (TransactionScope scope = new TransactionScope())

{

try

{

newSongId = this.CreateNewSong(newSong); // First create the new song....

returnValue = this.AddSongToCd(cdId, newSongId, 0); // then add new song to cd....

}

catch (Exception ex)

{

errMsg = ex.Message;

}

scope.Complete();

}

Each of the 2 lines within "try" stmt (CreateNewSong and AddSongToCd) call a SQL stored procedure, and I know that these 2 calls work. For testing, I am intentionally sending in an invalid cdId to force the 2nd call to fail (AddSongToCd). When I do this, the AddSongToCd() call does indeed fail and the exception is caught by the "catch" stmt. However, the CreateNewSong() does not get rolled back, the song is created but not added to the cd. Shouldn't the scope.Complete() stmt rollback so that the song does not get created if the 2nd stmt fails



Answer this question

TransactionScope commits even tho exception was thrown

  • GranBosco

    You catch any exception, catching it and not rethrowing it just makes the exception disappear. So scope.Complete() will always be called!

    Put scope.Complete(); at the end of the try block, so that it is only called when all code in the try block succeeded.

    --
    SvenC


  • Sebastiang

    I see that it works if I do this instead...

    if (returnValue == true)

    scope.Complete();

    but none of the examples I see do this. What is the best way to handle this


  • Robert3234

    That makes sense, thanks!
  • TransactionScope commits even tho exception was thrown