views:

292

answers:

3

Is it possible to have a hierarchy of transaction scopes?

If the outer transaction scope does a dispose, what will happen to changes made in the inner transaction scope?

My particular problem is that I have test code that runs code that has a transaction scope. When I call a second set of code with a transaction scope I get "Cannot access a disposed object. Transaction". Could it be that the dispose of the inner transaction scope is also disposing the outer transaction scope.

+2  A: 

I doubt this is what is happening. TransactionScopes can be nested as long as the underlying technology supports distributed transactions, if necessary. For instance, if you start a transaction and update some data in database A, and then you call a function, and inside that function, you create a new TransactionScope and insert some data into database B, then the inner transaction uses the "ambient" transaction that was already open. However, for this to work you need the Distributed Transaction Coordinator running (for SQL Servers). Also, SQL Server 2005 and above has the ability to start a transaction as a regular transaction and promote it to a distributed transaction if it needs to, whereas SQL 2000 will start all of them as distributed transactions because it doesn't have the ability to promote them.

When you have nested transactions, the whole transaction doesn't commit until the outer-most transaction is committed.

Here's some more info.

Take a look at TransactionScopeOption; that determines how the nested transaction interacts with outer transactions.

Scott Whitlock
+2  A: 

When an outer transaction fails, all the inner ones will we rolled back. If you commit and inner one, and dispose the outer, the inner still rolls back. In fact the inner doesn't commit unless the outer one lets it by committing.

You are committing the outer one aren't you? See here for a good paper on this.

Preet Sangha
+1  A: 

Yes, it's possible to have a hierarchy of transaction scopes. This blog post explains how they work, in particular how the inner transaction scope should be instantiated and how the transactions complete & commit.

It is important to keep in mind the distinction between transactions and transaction scopes - by default (i.e. in the absense of TransactionScopeOption) you will only utilise a single transaction even when you nest transaction scopes.

Regarding the "disposed" error message, see this question.

romkyns