views:

462

answers:

2

Under what circumstances can code wrapped in a System.Transactions.TransactionScope still commit, even though an exception was thrown and the outermost scope never had commit called?

There is a top-level method wrapped in using (var tx = new TransactionScope()), and that calls methods that also use TransactionScope in the same way.

I'm using typed datasets with associated tableadapters. Could it be that the commands in the adapter aren't enlisting for some reason? Do any of you know how one might check whether they are enlisting in the ambient TransactionScope or not?

A: 

The obvious scenario would be where a new (RequiresNew) / null (Suppress) transaction is explicitly specified - but there is also a timeout/unbinding glitch that can cause connections to miss the transaction. See this earlier post (the fix is just a connection-string change), or full details.

Marc Gravell
I tried the connection string change earlier on while researching my problem and it didn't help in this case. I think I might have `RequiresNew` somewhere, so I'll take a look.
Neil Barnwell
I'm using typed datasets with associated tableadapters. Could it be that the commands in the adapter aren't enlisting for some reason? Do you know how one might check whether they are enlisting in the ambient TransactionScope or not?
Neil Barnwell
I found the answer in the end - to do with the order that transactionscope and connection objects are created. I've added my answer to this post.
Neil Barnwell
+3  A: 

The answer turned out to be because I was creating the TransactionScope object after the SqlConnection object.

I moved from this:

using (new ConnectionScope())
using (var transaction = new TransactionScope())
{
    // Do something that modifies data

    transaction.Complete();
}

to this:

using (var transaction = new TransactionScope())
using (new ConnectionScope())
{
    // Do something that modifies data

    transaction.Complete();
}

and now it works!

So the moral of the story is to create your TransactionScope first.

Neil Barnwell
It also shows the value of posting code ;-p We might have spotted it for you; never mind - sorted now.
Marc Gravell
Yeah but I couldn't do that in this case, as the app is too complex, and I hadn't replicated it in a smaller example.
Neil Barnwell
I think you can create the SqlConnection first (in case you need to pass it around to methods that all use TransactionScope. In the situation where you have an existing connection already and want to create a transaction scope, you can just call connection.ElistTransaction( Transaction.Current ) inside the using block for the scope.
Triynko
Couple of hours saved.. thx.
Aseem Gautam