2012-06-25 38 views
8

我已經做了很多搜索,但找不到一個直的anwser。實體框架:如何在事務中放置多個存儲過程?

我有兩個存儲過程,他們都進行了功能導入到的DbContext對象

  1. INSERTA()
  2. InsertB()

我希望把他們的交易。 (即如果InsertB()失敗,回滾InsertA())

我該怎麼做?我可以只聲明一個TransactionScope對象幷包裝兩個存儲過程嗎?

感謝

+0

你爲什麼不創建一個包裝存儲過程,要麼調用交易或這兩個程序,如果這些程序總是一起調用,那麼首先將邏輯合併爲一個單獨的過程? –

+0

這兩個過程是遺留代碼。他們都很大。 – c830

+0

好的,但你仍然可以編寫一個非常小的程序作爲包裝。 –

回答

13

你需要爭取在交易範圍的操作如下:

using(TransactionScope tranScope = new TransactionScope()) 
{ 
    InsertA(); 
    InsertB(); 

    tranScope.Complete(); 
} 

錯誤時,交易範圍將自動回滾。當然,您仍然需要處理異常,並執行您的異常處理設計規定(日誌等)。但是,除非您手動撥打Complete(),否則當using範圍結束時,事務將回滾。

除非您在同一事務範圍內打開其他數據庫連接(請參閱here),否則事務範圍將不會提升爲分佈式事務。

這是重要的是要知道因爲否則你需要配置MSDTC在此操作涉及的所有服務器(網絡,最終中間層,sql服務器)。所以,只要交易沒有提升到分佈式交易,你就會沒事的。

注: 爲了微調您的交易選項,如超時和隔離級別,看看this TransactionScope constructor。默認隔離級別是可序列化的。

附加樣本:here

+0

感謝您的詳細解答。 – c830

4

您可以使用TransactionScope對象,也可以使用SqlConnection.BeginTransaction方法。要小心使用TransactionScope,在調用另一個數據庫中的存儲過程時,事務可以被保存到分佈式事務中。事務可能是資源密集型的。

如何使用sqlConnection.BeginTransaction ...(http://msdn.microsoft.com/en-us/library/86773566.aspx)

private static void ExecuteSqlTransaction(string connectionString) 
{ 
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    { 
     connection.Open(); 

     SqlCommand command = connection.CreateCommand(); 
     SqlTransaction transaction; 

     // Start a local transaction. 
     transaction = connection.BeginTransaction("SampleTransaction"); 

     // Must assign both transaction object and connection 
     // to Command object for a pending local transaction 
     command.Connection = connection; 
     command.Transaction = transaction; 

     try 
     { 
      command.CommandText = 
       "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"; 
      command.ExecuteNonQuery(); 
      command.CommandText = 
       "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"; 
      command.ExecuteNonQuery(); 

      // Attempt to commit the transaction. 
      transaction.Commit(); 
      Console.WriteLine("Both records are written to database."); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Commit Exception Type: {0}", ex.GetType()); 
      Console.WriteLine(" Message: {0}", ex.Message); 

      // Attempt to roll back the transaction. 
      try 
      { 
       transaction.Rollback(); 
      } 
      catch (Exception ex2) 
      { 
       // This catch block will handle any errors that may have occurred 
       // on the server that would cause the rollback to fail, such as 
       // a closed connection. 
       Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType()); 
       Console.WriteLine(" Message: {0}", ex2.Message); 
      } 
     } 
    } 
} 

如何使用的TransactionScope ...(HTTP ://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx)

// This function takes arguments for 2 connection strings and commands to create a transaction 
// involving two SQL Servers. It returns a value > 0 if the transaction is committed, 0 if the 
// transaction is rolled back. To test this code, you can connect to two different databases 
// on the same server by altering the connection string, or to another 3rd party RDBMS by 
// altering the code in the connection2 code block. 
static public int CreateTransactionScope(
    string connectString1, string connectString2, 
    string commandText1, string commandText2) 
{ 
    // Initialize the return value to zero and create a StringWriter to display results. 
    int returnValue = 0; 
    System.IO.StringWriter writer = new System.IO.StringWriter(); 

    try 
    { 
     // Create the TransactionScope to execute the commands, guaranteeing 
     // that both commands can commit or roll back as a single unit of work. 
     using (TransactionScope scope = new TransactionScope()) 
     { 
      using (SqlConnection connection1 = new SqlConnection(connectString1)) 
      { 
       // Opening the connection automatically enlists it in the 
       // TransactionScope as a lightweight transaction. 
       connection1.Open(); 

       // Create the SqlCommand object and execute the first command. 
       SqlCommand command1 = new SqlCommand(commandText1, connection1); 
       returnValue = command1.ExecuteNonQuery(); 
       writer.WriteLine("Rows to be affected by command1: {0}", returnValue); 

       // If you get here, this means that command1 succeeded. By nesting 
       // the using block for connection2 inside that of connection1, you 
       // conserve server and network resources as connection2 is opened 
       // only when there is a chance that the transaction can commit. 
       using (SqlConnection connection2 = new SqlConnection(connectString2)) 
       { 
        // The transaction is escalated to a full distributed 
        // transaction when connection2 is opened. 
        connection2.Open(); 

        // Execute the second command in the second database. 
        returnValue = 0; 
        SqlCommand command2 = new SqlCommand(commandText2, connection2); 
        returnValue = command2.ExecuteNonQuery(); 
        writer.WriteLine("Rows to be affected by command2: {0}", returnValue); 
       } 
      } 

      // The Complete method commits the transaction. If an exception has been thrown, 
      // Complete is not called and the transaction is rolled back. 
      scope.Complete(); 

     } 

    } 
    catch (TransactionAbortedException ex) 
    { 
     writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message); 
    } 
    catch (ApplicationException ex) 
    { 
     writer.WriteLine("ApplicationException Message: {0}", ex.Message); 
    } 

    // Display messages. 
    Console.WriteLine(writer.ToString()); 

    return returnValue; 
} 
+0

但是,使用正確的事務支持,只需幾行代碼即可完成大量代碼。 –