Share via


How to: Save data by using a transaction

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. 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.

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.

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 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
    
    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();
    }
    

See also