2013-02-07 122 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); 
      } 
     } 
    } 
}