Uređivanje

Dijeli putem


Save data by using a transaction in .NET Framework applications

Note

Datasets and related classes are legacy .NET Framework technologies from the early 2000s that enable applications to work with data in memory while the applications are disconnected from the database. The technologies are especially useful for applications that enable users to modify data and persist the changes back to the database. Although datasets have proven to be a very successful technology, we recommend that new .NET applications use Entity Framework Core. Entity Framework provides a more natural way to work with tabular data as object models, and it has a simpler programming interface.

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