EnlistDistributedTransaction —
EnlistDistributedTransaction(ITransaction transaction
);
If auto-enlistment is disabled, this method enlists the
Connection
in the specified active distributed
transaction. If the transaction is committed or rolled back, all
modifications made to the data source using the
Connection
are also committed or rolled back.
The following example shows how to enlist a
Connection
in a distributed transaction and how to
vote to commit or abort the transaction based on the success or
failure of a Command
executed against the data
source:
// create the connection with auto-enlistment disabled SqlConnection conn = new SqlConnection( "Data Source=localhost;Integrated Security=SSPI;" + "Initial Catalog=Northwind;Enlist=false;"); SqlCommand cmd = new SqlCommand(); //... define the command to update the data source conn.Open(); // get the current COM+ DTC transaction, // and enlist the connection if the transaction exists ITransaction tran = (ITransaction)ContextUtil.Transaction; if(tran != null) conn.EnlistDistributedTransaction(tran); try { // execute the command against the data source cmd.ExecuteNonQuery(); // vote to commit after successful command ContextUtil.SetComplete(); } catch (SqlException ex) { // vote to roll back if an error occurs ContextUtil.SetAbort(); } finally { conn.Close(); }
Auto-enlistment is disabled for the Connection
using the connection string parameter Enlist=false
for a SqlConnection
or using the connection string
parameter OLE
DB Services=-7
for an OleDbConnection
.
The Connection
must be open prior to calling
EnlistDistributedTransaction()
. An exception is
raised if the Connection
has already started a
transaction with BeginTransaction()
. If, however,
a local transaction at the data source exists, it’s
rolled back without notification, and the
Connection
is enlisted in the distributed
transaction.