Is a transaction opened?

G

Guest

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!
 
M

Marc Gravell

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
 
M

Marc Gravell

terminology slipup; I may have confused my words - this isn't
necessarily "declarative" - however, it is still very simple and
effective to do!

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Using transaction with multiple commands 5
SqlConnection 2
tables search 2
ADO.NET rollbacks 2
OOP advice needed 13
"Invalid attempt to read when no data is present" 4
blob 9
Error while running asp.net 3

Top