Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data committed even though System.Transactions.TransactionScope.Commit() not called

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?

like image 900
Neil Barnwell Avatar asked Nov 10 '09 12:11

Neil Barnwell


2 Answers

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.

like image 56
Neil Barnwell Avatar answered Oct 20 '22 02:10

Neil Barnwell


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.

like image 39
Marc Gravell Avatar answered Oct 20 '22 02:10

Marc Gravell