Share via


Save data by using a transaction

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

You save data in a transaction by 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.

Note

The System.Transactions namespace is supported in Windows 2000 or later.

The easiest way to implement a transaction is to instantiate a TransactionScope object in a using statement. (For more information, see Using Statement, and using Statement.) The code that runs within the using statement participates 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 Save data in a transaction.

To add a reference to the System.Transactions dll

  1. On the Project menu, select Add Reference.

  2. On the .NET tab (SQL Server tab for SQL Server projects), select System.Transactions, and then select 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();
    }
    
    Using updateTransaction As New 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()
    End Using
    

See Also

Save data back to the database