Using A Single Transaction With Multiple Typed DataSets

Provides a detailed explanation of how to implement a single transaction across multiple Typed Datasets

Introduction

If you have ever used Typed DataSets, you know how fast and easy they can make database access programming. The only drawback I ever ran into while using them is when I needed to put actions associated with several different Typed DataSets into a single Transaction.

Background

Transactions and Typed DataSets are nothing new. However, when you want to place Updates to more than one database table through different Typed DataSets into a single transaction, things get a little more complicated. Hopefully, this article will help to explain that complexity and provide you with some generic class objects you can incorporate into your project with a few trivial modifications.

After searching the Web for hours and only finding a couple examples (which I couldn't get to work), I was forced to figure out my own way to accomplish this seemingly simple task. Let me tell you, the code you see here in this article took many hours to figure out and get working reliably. I am posting this article because there was so little information available on this topic on the Web that it seemed like an article on the topic would benefit the development community.

Using the Code

The Typed DataSet Extender Class code shown in this article is added to each Typed DataSet's TableAdapter class you want to be able to enlist in the Transaction. The TableAdapter's Partial Class file is automatically created in Visual Studio 2005 by simply double-clicking on the Typed DataSet design surface. I believe you can also right click on Typed DataSet in the Solution Explorer and choose the "View Code" option.

Unfortunately, the Auto-Generated code does not create the NameSpace or TableAdapter's Partial Class so you'll have to do that manually for each Typed DataSet you want to enlist in the Transaction. The code shown below will be copied into each Typed DataSet's Partial Class file created when you double-click on the Typed DataSet Design surface (the filename will be <TypedDataSetName>.vb).

Modifying the code below to extend your Typed DataSet classes is done by simply replacing the <TypedDataSetName> tags (including the brackets < >) in the class example shown below with the name of your Typed DataSet (the DataSet name without the XSD extension). You will need to copy the extender code below into every Typed DataSet class you want to use with a single Transaction. You'll only need to change the <TypedDataSetName> tags to match the name of the Typed DataSet, the rest of the code does not require any changes to work with your Typed DataSets.

Since this extender code is placed in a Partial Class, it will not be lost when the Typed DataSet is modified or rebuilt so this effort only needs to be done once (and for any additional Typed DataSets you add to your project in the future). This is the power of the Partial Class and is what makes it possible for you to have a Transaction that spans across multiple Typed DataSets without invoking a Distributed Transaction like using TransactionScope does.

The code shown below is the DAL Interface Class required to facilitate the Transaction sharing across multiple Typed DataSets. Just create an SqlInterface.vb file, paste all the code below into it and add it to your project - you will also need to add the required Imports to support any TableAdapter methods you may use in this class to retrieve data from the database.

Placing all the Typed DataSet Fill methods in the SqlInterface Class provides a single access point for Data Access and eliminates a lot of unnecessary complexity in your application code that would be required to handle Multi-Typed DataSet Transaction participation.

Imports System.Data.SqlClient
PublicClass SqlInterface
#Region " Singleton Constructor Methods "
'Private Shared reference to this Class required to provide a Singleton instance
PrivateShared SqlInterfaceInstance As SqlInterface
'Provides a Singleton reference to this Class Instance
PublicSharedFunction GetInstance() As SqlInterface
If (IsNothing(SqlInterfaceInstance)) Then
SqlInterfaceInstance = New SqlInterface()
EndIfReturn SqlInterfaceInstance
EndFunction'Private Class Constructor called by the Shared Singleton GetInstance Method
PrivateSubNew()
'Do not remove this sub. This prevents someone from instantiating another
'SqlInterface Class Instance. Call the 'GetInstance()' method to get an
'instance reference to this Class. This enforces a Singleton Pattern.
EndSub#End Region
#Region " Private Class Variables "
Private _UsingTransaction AsBoolean = FalsePrivate _Transaction As SqlTransaction = NothingPrivate _TransConnection As SqlConnection = NothingPrivate _TableAdapter As SqlDataAdapter = NothingPrivate _TransCommand As SqlCommand = Nothing#End Region
#Region "Transaction Methods"
'Initiates a Transaction on a Typed DataSet TableAdapter Connection. This
'transaction is automatically assigned to any other Typed DataSet TableAdapter
'initialized through this Interface Class during an active Transaction until
'the transaction is explicitly Committed or Rolled back through the SqlInterface
'Class Instance. (Note: The Private Scope of this method is intentional)
PrivateFunction BeginTransaction(ByVal TableAdapter As SqlDataAdapter) AsBoolean'Be sure we don't already have a transaction initiated
If (Not IsNothing(_Transaction)) ThenReturnFalse'Set Class TableAdapter Object
_TableAdapter = TableAdapter
'Set Class Connection Object
If (Not IsNothing(_TableAdapter.UpdateCommand)) Then
_TransConnection = _TableAdapter.UpdateCommand.Connection
ElseIf (Not IsNothing(_TableAdapter.InsertCommand)) Then
_TransConnection = _TableAdapter.InsertCommand.Connection
ElseIf (Not IsNothing(_TableAdapter.DeleteCommand)) Then
_TransConnection = _TableAdapter.DeleteCommand.Connection
ElseIf (Not IsNothing(_TableAdapter.SelectCommand)) Then
_TransConnection = _TableAdapter.SelectCommand.Connection
ElseThrowNew Exception("A Connection could not be established _
because no Command Object has been initialized")
EndIf'Open the DB Connection
_TransConnection.Open()
'Set the Class Transaction Object
_Transaction = _TransConnection.BeginTransaction()
'Set the Transaction property for any instantiated Command Objects
If (Not IsNothing(_TableAdapter.UpdateCommand)) _
Then _TableAdapter.UpdateCommand.Transaction = _Transaction
If (Not IsNothing(_TableAdapter.InsertCommand)) _
Then _TableAdapter.InsertCommand.Transaction = _Transaction
If (Not IsNothing(_TableAdapter.DeleteCommand)) _
Then _TableAdapter.DeleteCommand.Transaction = _Transaction
If (Not IsNothing(_TableAdapter.SelectCommand)) _
Then _TableAdapter.SelectCommand.Transaction = _Transaction
ReturnTrueEndFunction'This method enlists Adapters used for Database Select
'Operations during an active Transaction into the current
'Transaction and Connection so the Select operation is not blocked
'by the active Update Transaction.
'This is required because the Auto-Generated TableAdpater Class
'is coded in such a way that the DataAdapter's
'SelectCommand is not initialized like the
'Update, Insert and Delete Command Objects. The SelectCommand is instead
'added to the TableAdapater internal CommandCollection
'(it's the ONLY Command object in the collection). So this is
'somewhat of a hack to work around this but at least
'it keeps all the necessary code confined to the TableAdapter
'Extension Class and this DAL Interface Class eliminating the need
'for any complicated code in the general application.
PrivateSub EnlistAdapterInTransaction(ByVal Adapter AsObject)
Adapter.SelectCommand.Transaction = Me._Transaction
Adapter.SelectCommand.Connection = Me._TransConnection
EndSub'Commits all DB changes performed during the Transaction and releases
'all resources and SQL DB connections.
PublicFunction CommitTransaction() AsBooleanIf (Not IsNothing(_Transaction)) Then
_Transaction.Commit()
EndTransaction()
ReturnTrueElse
EndTransaction()
ReturnFalseEndIfEndFunction'Rolls back all DB changes performed during the Transaction and
'releases all resources and SQL DB connections.
PublicFunction RollBackTransaction() AsBooleanIf (Not IsNothing(_Transaction)) Then
_Transaction.Rollback()
EndTransaction()
ReturnTrueElseReturnFalseEndIfEndFunction'Handles cleanup for a DAL initiated transaction
PrivateSub EndTransaction()
If (Not IsNothing(_TransConnection)) Then _TransConnection.Close()
If (Not IsNothing(_Transaction)) Then _Transaction.Dispose()
If (Not IsNothing(_TableAdapter)) Then _TableAdapter.Dispose()
EndSub#End Region
#Region " Public Class Methods "
'Example method that executes a Select Operation on the DataBase
'with a check for an active
'transaction. If a transaction is active on the Connection,
'the SelectCommand object from
'the TableAdapter is enlisted into that Transaction
'so it is not blocked by the active Transaction.
'Note: The Typed DataSet name shown in the example is 'TdSomeData'
PublicFunction GetSomeDataByKey(ByVal Key AsInteger) As TdSomeDataDataTable
Dim TdAdapter AsNew TdSomeDataAdapter
'See if an active transaction exists on the DAL and enlist
'the TableAdapter in the Transaction if there is.
If (Not IsNothing(Me._Transaction)) Then EnlistAdapterInTransaction(TdAdapter)
Return (TdAdapter.GetSomeData(Key))
EndFunction#End Region
#Region " Public Class Properties "
'This Property provides access to an active Transaction object
'regardless of what Typed DataSet initiated the transaction.
PublicReadOnlyProperty Transaction(ByVal TableAdapter As SqlDataAdapter) _
As SqlTransaction
GetIf ((Me.UsingTransAction) AndAlso (IsNothing(_Transaction))) ThenMe.BeginTransaction(TableAdapter)
EndIfReturn (_Transaction)
EndGetEndProperty'Class flag indicating a Transaction is to be used for
'subsequent DB changes until committed or rolled back.
'This flag is required to initiate a transaction on
'subsequent TableAdapter reads/writes on the underlying Database.
'The SqlInterface Class Instance (DAL Interface) will
'automatically initiate and maintain the Command, Connection and
'Transaction objects across multiple Typed DataSet TableAdapter
'interactions with the Database until the Transaction
'is explicitly Committed or Rolled back. Setting this property to True
'automatically begins a transaction when required.
PublicProperty UsingTransAction() AsBooleanGetReturn (_UsingTransaction)
EndGetSet(ByVal value AsBoolean)
_UsingTransaction = value
EndSetEndProperty#End Region
EndClass

Here's an example of how to use the SQLInterface Class in your general application code:

'Declare a local Class variable of the SQLInterface Class
'(you don't have to do this - you can use SqlInterface.GetInstance
'if you like, I just like shorter method call strings.
'So in the example method below, you could use:
'SqlInterface.GetInstance.UsingTransAction = True
'if you prefer not to use a Class variable like I did in my example.
Private SQL As SqlInterface = SqlInterface.GetInstance
PublicSub Save()
Try'Set the DAL Interface Transaction Flag.
'This instructs the SqlInterface Class to begin a transaction
'or enlist in an existing active transaction when the
'SqlInterface Transaction Property is accessed.
'As long as this flag was True the first time the
'SqlInterface Transaction property was assigned to a
'Typed DataSet's TableAdapter Transaction property,
'any other Typed DataSets that assign the SqlInterface
'transaction property to their transaction property will
'automatically be enlisted in the existing Transaction
'even if the 'UsingTransAction' flag has been reset to False.
'To terminate an existing SqlInterface Transaction,
'you MUST call either the SqlInterface CommitTransaction or
'RollBackTransaction method.
'Note that either of these methods will reset the 'UsingTransAction' flag.
SQL.UsingTransAction = True'Do some code processing here that will cause the Typed DataSet
'to Modify a Table the DB. To use the
'MyTypedDataSetAdapter in the method below, we would need to have an
'Imports Statement at the top of
'this Class file something like this:
'Imports <Solution Name><solutionname />.MyTypedDataSetTableAdapter
If (Me.HasChanges) ThenDim TdAdapter AsNew MyTypedDataSetAdapter
'Assign the SqlInterface Transaction to the TableAdapter
'Transaction Property if the 'UsingTransaction'
'Flag has been previously set, this line of code will either
'begin a transaction or enlist this Typed
'DataSet's TableAdapter in the current Transaction that was
'initiated by another Typed DataSet
'participating in this Transaction.
If (SQL.UsingTransAction) Then TdAdapter.Transaction =
SQL.Transaction(TdAdapter.GetAdapter())
'Call the Update Method to save Data to the DB
TdAdapter.Update(Param1, Param2, Param3)
EndIf'Commit the Transaction
SQL.CommitTransaction()
Catch ex As Exception
'Something went wrong, Rollback the Transaction
SQL.RollBackTransaction()
'Throw the Exception so it can be caught and displayed if required
Throw ex
EndTryEndSub

That's it! If you've been avoiding the use of Typed DataSets because you didn't think you could use a single transaction for multiple Typed DataSet updates without using the costly Transaction scope, I hope this article changes your mind. I have found Typed DataSets to be a powerful feature of the .NET Framework handling most of the underlying complexities of database interaction. Typed DataSets make updating your code easy as the underlying database schema changes with the evolution of your application. I hope you find these classes to be useful!

Points of Interest

Something I learned while developing this idea that surprised me was that the SelectCommand object is not used by the Typed DataSet Adapter Class. I found it even more strange that the auto-generated code only placed the SelectCommand object in the CommandObject collection and did not place any of the other Command objects in the collection. The reference to each of them was assigned to their respective command objects (Update, Insert, Delete).

I was searching about sharing same transaction into multiple sqldataadapter and found your article.

Reading it, I was also wondering about your singleton.

You have a unique instance of SqlInterface, so what if a user keep clicking and refreshing a page ?Will it force a new server side construction of the page (so for example 3 "threads" if the user refresh 3 times) and so the 3 threads will use the same SqlInterface instance ?

This was a remark for a single user connecting to your web site, but also what if multiple users ?

I am not familiar with the term "thread safe" so I have to read documentation.

so perhaps I am wrong, but if not :

- perhaps not use a singleton- perhaps make it thread safe

For my work, I think I will not use singleton but just have a setter for the transaction in all my SqlDataAdapters (typed data sets), and use the setter where I need it (hope I will succeed)

The reference to being thread safe means the potential exists that a deadlock condition could occur if 2 different threads attempt to instantiate the SqlInterface class at the same time. From the research I have done on this, there seems to be a lot of confusion about how the .Net framework handles this.

Some articles say the framework deals with this gracefully choosing a victim thread that will get blocked while allowing the other thread to successfully initialize the SqlInterface instance. Other articles I read say this isn't true and that you must use synchronization, locking or a Mutex to solve the deadlock condition

From all my research, it seemed to me that using a Mutex would solve that problem and I just haven't had the time to update my article but I have at least done some of the research.

A singleton constructor was chosen so that transaction data (connection, command, transaction state) could be maintained after the intiating Typed Dataset Adapter completed it's Database activity. Then it can be passed over to the next Typed DataSet's adapter instance so it's activity would be contained within the same transaction.

Since each page refresh would receive the very same SqlInterface instance (regardless of how many threads are initialized) the same transaction data is made available to the page objects to interact with which will have the desired effect of keeping all of the Typed DataSet's Database interaction within the transaction initiated by the first Typed DataSet.

Unless you are using a multithreaded application, this should work just the way it stands. I am using this code myself and it works perfectly. Feel free to experiment with it and if you find a better way to do this, share it with us all on the Code Project!

Then I just call my AttachTransaction wherever I want in any TableAdapters I need.

Note that I work with Datasets and also TableAdapter of my own which I coded inpiring from the generated code of dataset made with the designers. So in both partial class or class of my own, I use the AttachTransaction when needded.

I don't know C# too well but it looks like it would work to me. I like the simplicity of your design. When I have a little free time, I will try your design in my application and see if it works for me. It's a lot easier to use than my design and simple is always better in programming. Nice job, maybe you should write an article!!!