I'm trying to add transaction support to our database object. This object is a Remoting object. (this to ensure that on the Windows Client, no database connection is required.)
Now I want to add support for transactions; Basically, a client will need to use it like this;
- BeginTransaction
- ExecuteNonQuery("insert...")
- ExecuteNonQuery("insert...")
- Commit / Rollback
Public Function ExecuteNonQuery(ByVal Query As String) As Integer
Dim intResult As Integer = -1
Using conn As New SqlConnection(Me.strConnectionString)
Using cmd As New SqlCommand(Query, conn)
conn.Open()
intResult = cmd.ExecuteNonQuery()
End Using
End Using
Return intResult
End Function
So the problem I have is that I can't really create a transaction when I use a new connection (using conn...
) in the method above.
So I think I need to move the SqlConnection instance outside of the method and change it into a class-level variable. But this is not best-practice I think. (?) Besides: executing a lot of queries in sequence results in an error: 'internal fatal error'.
Is there anybody who can point me in the right direction? All examples I've found online cover transactions in its simplest way by executing several queries directly in sequence.
edit: it's a little bit like this question. (How to use a single SqlTransaction for multiple SqlConnections in .NET?) . So maybe it is just not possible, but is there a workaround?
edit 2: It also seems that this 'internal fatal error' is raised because the object is used in parallel. Maybe that's just not possible?