共用方式為


如何:使用異動儲存資料

 

發行︰ 2016年4月

您可以使用 System.Transactions 命名空間 (Namespace),在交易中儲存資料。 請使用 TransactionScope 物件,加入自動為您管理的交易。

由於專案建立時並沒有 System.Transactions 組件的參考,所以您必須在使用交易的專案中手動加入參考。

注意

Windows 2000 (含) 以後版本才支援 System.Transactions 命名空間。

實作交易最簡單的方式就是在 using 陳述式中具現化 TransactionScope 物件 (如需詳細資訊,請參閱 Using StatementUsing 陳述式)。 在 using 陳述式中執行的程式碼將會加入交易。

若要認可交易,請呼叫 Complete 方法,做為 using 區塊中的最後一項陳述式。

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

如需詳細資訊,請參閱 逐步解說:在異動中儲存資料

若要加入 System.Transactions dll 的參考

  1. 在 [專案] 功能表中選擇 [加入參考]。

  2. 選取 [.NET] 索引標籤中的 [System.Transactions] (SQL Server 專案則為 [SQL Server] 索引標籤),然後按一下 [確定]。

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

請參閱

逐步解說:在異動中儲存資料
將 Windows Form 控制項繫結至 Visual Studio 中的資料
Visual Studio 資料應用程式的概觀
連接至 Visual Studio 中的資料
準備您的應用程式以接收資料
將資料擷取至您的應用程式中
將控制項繫結至 Visual Studio 中的資料
在您的應用程式中編輯資料
驗證資料
儲存資料