2

I'm facing this issue today. I made an API with .NET Core and I created a function to insert records into a SQL Server database.

SqlCommand.ExecuteNonQuery returns 1, but when I make a SELECT directly from SQL Server Management Studio, that returns 0 rows. To be precise, SELECT returns only the rows inserted manually with SQL Server Management Studio.

If I try to insert another row from SQL Server Management Studio, I can see that the primary key (ID autoincrement) is increasing even if I don't have that row.

My code:

public async Task<bool> InsertAuditTrail(AuditTrailModel auditTrail)
{
        bool result = false;
        string commandText = String.Concat(@"INSERT INTO [dbo].[AuditTrail] ", 
                                                   "([NomeApplicazione],[N_Applicazione],[N_Record],[NomeTabella],[NomeCampo],[Utente],[Data],[Insert],[Delete],[Update],[DatoPrecedente],[DatoAggiornato]) ",
                                            "VALUES (@NomeApplicazione, @N_Applicazione, @N_Record, @NomeTabella, @NomeCampo, @Utente, @Data, @Insert, @Delete, @Update, @DatoPrecedente, @DatoAggiornato)");
                  

        using (var connection = new SqlConnection(connStr))
        {
            await connection.OpenAsync(); 
            using (var transaction = connection.BeginTransaction())
            {
                using (var command = new SqlCommand(commandText, connection, transaction))
                {
                    try
                    {
                        command.CommandType = CommandType.Text;
                        command.Parameters.AddWithValue("@NomeApplicazione", auditTrail.NomeApplicazione);
                        command.Parameters.AddWithValue("@N_Applicazione", auditTrail.N_Applicazione);
                        command.Parameters.AddWithValue("@N_Record", auditTrail.N_Record);
                        command.Parameters.AddWithValue("@NomeTabella", auditTrail.NomeTabella);
                        command.Parameters.AddWithValue("@NomeCampo", auditTrail.NomeCampo);
                        command.Parameters.AddWithValue("@Utente", auditTrail.Utente);
                        command.Parameters.AddWithValue("@Data", auditTrail.Data);
                        command.Parameters.AddWithValue("@Insert", auditTrail.Insert);
                        command.Parameters.AddWithValue("@Delete", auditTrail.Delete);
                        command.Parameters.AddWithValue("@Update", auditTrail.Update);
                        command.Parameters.AddWithValue("@DatoPrecedente", auditTrail.DatoPrecedente);
                        command.Parameters.AddWithValue("@DatoAggiornato", auditTrail.DatoAggiornato);

                        result = command.ExecuteNonQuery() > 0 ? true : false;
                    }
                    catch (Exception Ex)
                    {
                        await connection.CloseAsync();
                        errorMsg = Ex.Message.ToString();                                               
                    }
                }
            }                          
        }    

        return result;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
vez25
  • 49
  • 6
  • Could you check the connectionstring used in the program against the one used in SSMS. Also look at this QA https://stackoverflow.com/questions/17147249/why-saving-changes-to-a-database-fails/17147460#17147460 – Steve Sep 11 '20 at 09:49
  • 6
    and where are you commiting transaction ? – Selvin Sep 11 '20 at 09:59
  • @Selvin transaction.COMMIT solved the problem!! Thank you – vez25 Sep 11 '20 at 10:34
  • 1
    @vez25, no need for an explict transaction with a single `INSERT` statement. Each statement is a single autocommit transaction by default; explict transactions are only needed with multiple statements. – Dan Guzman Sep 11 '20 at 10:43
  • And don't use [addwithvalue](http://www.dbdelta.com/addwithvalue-is-evil/) – SMor Sep 11 '20 at 12:39

1 Answers1

1

@Selvin pointed out the problem in a comment: The transaction needed to be committed. Even if the command executes successfully, the row won't be properly inserted until the transaction is committed. Leaving the using() statement doesn't commit it, either.

TarHalda
  • 1,050
  • 1
  • 9
  • 27