We recommend using Visual Studio 2017

Save data by using a transaction

 

For the latest documentation on Visual Studio 2017, see Save data by using a transaction on docs.microsoft.com. 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.

System_CAPS_ICON_note.jpg 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 thenselectOK.

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

Save data back to the database

Show: