TRANSACTION - How to correct a transport error?

1

I think you can understand what I'm trying to do there: This method will make a foreach for each item in my list of moves, and send each one as a parameter to the method that will save them in the DB.

I need to use a Transaction to ensure that all or all of these transactions are sent, or none, to ensure the consistency of the information.

I forced the execution of that method without the internet, to enter catch, and I encountered a problem in the line transaction.Rollback(); :

  

Additional information: A transport level error occurred while   send the request to the server. (provider: TCP Provider, error: 0 -   An existing connection was forced by the remote host.)

I thank you very much the charitable soul who has the time and good will to help this beginner:)

What am I doing wrong?

public static void SalvaNotaFiscalXML(IList<MovimentacaoDTO> movimentacoesNotaFiscal)
        {
            using (SqlConnection cnx = new SqlConnection(Properties.Settings.Default.CS1))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cnx.Open();
                    SqlTransaction transaction;
                    transaction = cnx.BeginTransaction("MovimentacaoDeEstoque");
                    try
                    {
                        cmd.Connection = cnx;
                        cmd.Transaction = transaction;


                        foreach (var item in movimentacoesNotaFiscal)
                        {
                            MovimentacaoBLL.NewMovimentacao(item);
                        }

                        transaction.Commit();
                        cnx.Close();
                        return;
                    }
                    catch (SqlException ex2)
                    {
                            transaction.Rollback();
                            cnx.Close();
                            throw ex2;
                    }
                }


            }
        }
    
asked by anonymous 27.09.2017 / 07:18

1 answer

1

Rollback will occur automatically if the connection to the database falls. That is, before running the rollback make sure the connection is open , doing so, if network crashes , Rollback will occur automatically, but if another type occurs , as an invalid die, you will need to run the rollback.

          catch (SqlException ex2)
                {
                        if (cnx.State == System.Data.ConnectionState.Open)
                        {
                           transaction.Rollback();
                           cnx.Close();
                        }
                        throw ex2;
                }
    
27.09.2017 / 21:23