Search code examples
c#ado.nettransactionscope

How can I separate my TransactionScopes so they don't interfere with each other?


I have some business logic that executes within a simple TransactionScope:

        using (var scope = new TransactionScope())
        {

            // does some logic.

            // then some more...

            scope.Complete();
        }

During execution an ADO exception occurs and the transaction is on it's way to being disposed.

In the meantime the exception is captured further upstream, and I try to log it to my database, via another connection.

At this point I get another error saying The operation is not valid for the state of the transaction.

Eeek!

Now I can see I am able to use IsolationLevel, to change the way my transactions interact, but is this the right thing to do? And which should I use?


Solution

  • Since your are mentioning multiple connections and the error you are referring to is something I have seen with DTC transactions I am guessing you are running DTC and that the state of the transaction is faulted due to the AdoException. Try putting a "RequiresNew" transaction scope around your logging code or post more of your code, its hard to see your architecture from that small snippet.

    Take a look at this answer showing how two connections can cause DTC to kick in based on which version of sql server you are running: TransactionScope automatically escalating to MSDTC on some machines?