2013-02-07 126 views
0

數據插入到數據庫中,我使用foreach循環

foreach(var x in items) 
{ 
    // enter code here 
} 

,並在我的代碼我發送數據到數據庫設在我items名單上有10條記錄我發送到數據庫的5發送後由於一些問題,將數據記錄失敗如何回滾所有我送到database數據。使用foreach循環

有沒有什麼辦法來處理這種情況 - 我使用實體數據模型

+0

你在你的數據庫操作中使用哪些類的例子嗎? –

回答

1

如何回滾所有我發送到數據庫中的數據。

使用事務與您的插入命令。如果你的目標數據庫是SQL服務器,那麼你會SqlTransactiontry/catch塊,這樣,如果發生異常,你可以Rollback交易。

從MSDN

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