This documentation is archived and is not being maintained.

How to: Save Data using a Transaction 

You save data in a transaction using the System.Transactions namespace. Use the TransactionScope object to participate in a transaction that is automatically managed for you.

Projects are not created with a reference to the System.Transactions assembly, so you need to manually add a reference to projects that use transactions.

NoteNote

The System.Transactions namespace is supported on Windows 2000 and later.

The easiest way to implement a transaction is to instantiate a TransactionScope object in a using statement. (For more information, see Using Statement (Visual Basic), and using Statement (C# Programming Guide).) The code executed within the using statement will participate in the transaction.

To commit the transaction, call the Complete method as the last statement in the using block.

To roll back the transaction, throw an exception prior to calling the Complete method.

For more information, see Walkthrough: Saving Data in a Transaction.

To add a reference to the System.Transactions dll

  1. From the Project menu, choose Add Reference.

  2. Select System.Transactions on the .NET tab (SQL Server tab for SQL Server projects) and click OK.

    A reference to System.Transactions.dll is added to the project.

To save data in a transaction

  • Add code to save data within the using statement that contains the transaction. The following code shows how to create and instantiate a TransactionScope object in a using statement:

    using (System.Transactions.TransactionScope updateTransaction = 
        new System.Transactions.TransactionScope())
    {
        // Add code to save your data here.
        // Throw an exception to roll back the transaction.
    
        // Call the Complete method to commit the transaction
        updateTransaction.Complete();
    }
    
    
    System.Transactions.TransactionScope updateTransaction =
    new System.Transactions.TransactionScope();
    {
        // Add code to save your data here.
        // Throw an exception to roll back the transaction.
    
        // Call the Complete method to commit the transaction
        updateTransaction.Complete();
    }
    
    

See Also

Show: