C# - SQL Server: INSERT statement conflicted with FOREIGN KEY constraint - Unhandled Exception

0

I wrote a small C# application, which reads an Excel file and should import the data into an existing SQL Server database.

As there is a foreign key constraint in the table the entries should be inserted to, I already prevented this error directly in my SQL query by using

IF NOT EXISTS (SELECT * FROM [dbo].[InvoiceAccount] 
               WHERE Caption = @Caption) 
    INSERT INTO [dbo].[InvoiceAccount] (Caption, IdInvoiceAccountType, Account)     
    VALUES (@Caption, @IdInvoiceAccountType, @Account)

On my development machine, executing my app and trying to insert an Excel sheet works fine without any issues.

As soon as I am doing the same on a different PC, I do get a ThreadExceptionDialog, although the SQL query works as expected.

The C# code looks like this:

foreach (DataGridViewRow row in dataGridViewToInsert.Rows)
{
    using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings.Get("connectionString")))
    {
        using (SqlCommand cmd = new SqlCommand("IF NOT EXISTS (SELECT * FROM [dbo].[InvoiceAccount] WHERE Caption = @Caption) INSERT INTO [dbo].[InvoiceAccount] (Caption, IdInvoiceAccountType, Account) VALUES (@Caption, @IdInvoiceAccountType, @Account)", con))
        {
            Debug.WriteLine(cmd.CommandText);

            cmd.Parameters.AddWithValue("@Caption", row.Cells[1].Value);

            switch (row.Cells[2].Value)
            {
                case "Erlöskonto":
                case "Revenue account":
                    cmd.Parameters.AddWithValue("@IdInvoiceAccountType", 1);
                    break;

                case "Kostenkonto":
                case "Expense Account":
                    cmd.Parameters.AddWithValue("@IdInvoiceAccountType", 2);
                    break;

                case "Geldkonto":
                case "Cash Account":
                    cmd.Parameters.AddWithValue("@IdInvoiceAccountType", 3);
                    break;

                case "Abschreibungskonto":
                case "Depreciation Account":
                    cmd.Parameters.AddWithValue("@IdInvoiceAccountType", 4);
                    break;

                default:
                    cmd.Parameters.AddWithValue("@IdInvoiceAccountType", 2);
                    break;
            };

            cmd.Parameters.AddWithValue("@Account", row.Cells[0].Value);

            con.Open();
            addedRows = cmd.ExecuteNonQuery();
            con.Close();
        }
    }

    if (addedRows > 0)
    {
        insertedRows = insertedRows + addedRows;
    }
}

So I really do not understand, what I am doing wrong here and why I only get the ThreadExceptionDialog only on other machines then my development PC.

What can I do to prevent this behaviour?


The exception:

System.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_VatType2InvoiceAccount_InvoiceAccount". The conflict occurred in database "easyjob", table "dbo.InvoiceAccount", column 'IdInvoiceAccount'.
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_VatType2InvoiceAccount_InvoiceAccount". The conflict occurred in database "easyjob", table "dbo.InvoiceAccount", column 'IdInvoiceAccount'.
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_VatType2InvoiceAccount_InvoiceAccount". The conflict occurred in database "easyjob", table "dbo.InvoiceAccount", column 'IdInvoiceAccount'.
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_VatType2InvoiceAccount_InvoiceAccount". The conflict occurred in database "easyjob", table "dbo.InvoiceAccount", column 'IdInvoiceAccount'.
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_VatType2InvoiceAccount_InvoiceAccount". The conflict occurred in database "easyjob", table "dbo.InvoiceAccount", column 'IdInvoiceAccount'.
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_VatType2InvoiceAccount_InvoiceAccount". The conflict occurred in database "easyjob", table "dbo.InvoiceAccount", column 'IdInvoiceAccount'.
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_VatType2InvoiceAccount_InvoiceAccount". The conflict occurred in database "easyjob", table "dbo.InvoiceAccount", column 'IdInvoiceAccount'.
The statement has been terminated.
The statement has been terminated.
The statement has been terminated.
The statement has been terminated.
The statement has been terminated.
The statement has been terminated.
   bei System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   bei System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   bei System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   bei System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   bei System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   bei System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   bei System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   bei ejDatabaseAnonymizer.MasterDataUserControl.buttonImport_Click(Object sender, EventArgs e)
   bei System.Windows.Forms.Control.OnClick(EventArgs e)
   bei System.Windows.Forms.Button.OnClick(EventArgs e)
   bei System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   bei System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   bei System.Windows.Forms.Control.WndProc(Message& m)
   bei System.Windows.Forms.ButtonBase.WndProc(Message& m)
   bei System.Windows.Forms.Button.WndProc(Message& m)
   bei System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   bei System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   bei System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
ClientConnectionId:d94a62b5-fb09-4d31-9561-76b2525c7321
Fehlernummer (Error Number):547,Status (State):0,Klasse (Class):16
c#
sql-server
constraints
thread-exceptions
asked on Stack Overflow Apr 7, 2020 by Gardinero • edited Apr 7, 2020 by Gardinero

2 Answers

0

"This error occurs when performing an INSERT command on a table and one of the columns of the table references a primary key on another table and the value being inserted to that particular column does not exist in the other table."

Check if the row referenced by the Foreign Key Exist.

See this, I believe it will help you: http://www.sql-server-helper.com/error-messages/msg-547-insert.aspx

answered on Stack Overflow Apr 7, 2020 by fsbflavio • edited Apr 7, 2020 by fsbflavio
0

Shame on me! The exception was caused by another sql query, which was called directly after the above one. So I was able to fix it.

But what I still do not understand is why the ThreadExceptionDialog did not appear on my development machine, although I also ran the exact same version on it...

Thanks for your help.

answered on Stack Overflow Apr 7, 2020 by Gardinero

User contributions licensed under CC BY-SA 3.0