共用方式為


在 .NET Framework 應用程式中使用交易儲存數據

備註

類別 DataSet 和相關類別是 2000 年代初的舊版 .NET Framework 技術,可讓應用程式在應用程式與資料庫中斷連線時使用記憶體中的數據。 這些技術特別適用於可讓使用者修改數據並將變更保存回資料庫的應用程式。 雖然數據集是經過證實的成功技術,但新 .NET 應用程式的建議方法是使用 Entity Framework Core。 Entity Framework 提供更自然的方式,以表格式數據作為物件模型使用,而且具有更簡單的程序設計介面。

您可以使用System.Transactions 命名空間將資料儲存在交易中。 使用TransactionScope物件參與由系統自動管理的交易。

不會使用 System.Transactions 元件的參考來建立專案,因此您必須手動新增使用交易之項目的參考。

實作交易最簡單的方式是在語句中實例化 TransactionScope 物件。 (如需詳細資訊,請參閱 Using語句Using語句。)在 using 語句內執行的程式碼會參與交易。

若要認可交易,請呼叫 Complete 方法作為using區塊中的最後一個語句。

若要復原交易,請在呼叫 Complete 方法之前擲回例外狀況。

若要新增 System.Transactions.dll 的引用

  1. 在 [專案] 功能表上,選取 [新增參考]

  2. 在 [.NETSQL Server 專案的 SQL Server] 索引標籤上,選取 [System.Transactions],然後選取 [確定]。

    System.Transactions.dll 的參考會新增至專案。

在交易中儲存數據

  • 新增程序代碼,以在包含交易的using語句內儲存數據。 下列程式代碼示範如何在 using 語句中建立和具現化 TransactionScope 物件:

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