Is a transaction opened? - CSharp
This is a discussion on Is a transaction opened? - CSharp ; How can I known if an SqlConnection has or not a transaction opened? I want
some code like this:
private SqlConnection conn;
private void Methode1()
{
SqlConnection conn = new SqlConnection(connectionText);
conn.Open();
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.Transaction = ...
-
Is a transaction opened?
How can I known if an SqlConnection has or not a transaction opened? I want
some code like this:
private SqlConnection conn;
private void Methode1()
{
SqlConnection conn = new SqlConnection(connectionText);
conn.Open();
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.Transaction = cmd.Connection.BeginTransaction();
Methode2();
cmd.Transaction.Commit();
conn.Close();
}
private void Methode2()
{
SqlCommand cmd = new SqlCommand(commandText, conn);
if (conn don't has an opened transaction)
{
cmd.Transaction = cmd.Connection.BeginTransaction();
// Some program
}
}
Thank you!
-
Re: Is a transaction opened?
> How can I known if an SqlConnection has or not a transaction opened?
Well, an alternative is to use declarative transactions and make life
easy for yourself...
i.e.
using(TransactionScope ts = new TransactionScope()) {
// perform some database activities, either in one method or 27
ts.Complete();
}
(note that on exception, Dispose() is called without Complete(), so
the transaction is aborted)
The important things is that declarative transactions nest correctly -
so if I call a method within a TransactionScope that *itself* creates
a TransactionScope, then the inner scope actually just enlists in the
single (outer) transaction - so all is committed as one. Additionally,
this will work correctly with both single-server and distributed
transactions.
One minor caveat; on Sql-2000 and below this will use DTC even for
single-server transactions, which has a small runtime overhead. On
Sql-2005 and above it will use an SQL transaction until it is forced
to escalate to DTC.
Marc
-
Re: Is a transaction opened?
terminology slipup; I may have confused my words - this isn't
necessarily "declarative" - however, it is still very simple and
effective to do!
Marc
Similar Threads
-
By Application Development in forum Microsoft Money
Replies: 1
Last Post: 07-29-2007, 05:37 PM
-
By Application Development in forum DOTNET
Replies: 2
Last Post: 10-29-2006, 03:05 PM
-
By Application Development in forum DOTNET
Replies: 0
Last Post: 03-26-2006, 10:31 AM
-
By Application Development in forum Commerce server
Replies: 5
Last Post: 02-03-2005, 05:21 AM
-
By Application Development in forum DOTNET
Replies: 4
Last Post: 03-05-2004, 06:04 AM