简体   繁体   English

C# - SQL 服务器:INSERT 语句与 FOREIGN KEY 约束冲突 - 未处理的异常

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

I wrote a small C# application, which reads an Excel file and should import the data into an existing SQL Server database.我编写了一个小型 C# 应用程序,它读取 Excel 文件,并将数据导入现有的 SQL 服务器数据库。

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由于表中应该插入条目的外键约束,我已经通过使用直接在我的 SQL 查询中防止了这个错误

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.在我的开发机器上,执行我的应用程序并尝试插入 Excel 表工作正常,没有任何问题。

As soon as I am doing the same on a different PC, I do get a ThreadExceptionDialog , although the SQL query works as expected.一旦我在另一台 PC 上执行相同操作,我就会得到一个ThreadExceptionDialog ,尽管 SQL 查询按预期工作。

The C# code looks like this: C# 代码如下所示:

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.所以我真的不明白,我在这里做错了什么以及为什么我只在其他机器上才获得ThreadExceptionDialog ,然后是我的开发 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

"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." “在对表执行 INSERT 命令并且表的列之一引用另一个表上的主键并且插入到该特定列的值在另一个表中不存在时,会发生此错误。”

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看到这个,相信会对你有所帮助: http://www.sql-server-helper.com/error-messages/msg-547-insert.aspx

Shame on me, The exception was caused by another sql query.真可惜,该异常是由另一个 sql 查询引起的。 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...但是我仍然不明白为什么ThreadExceptionDialog没有出现在我的开发机器上,尽管我也在它上面运行了完全相同的版本......

Thanks for your help.谢谢你的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#,SQL Server:INSERT语句与FOREIGN KEY约束冲突 - C#, SQL Server: The INSERT statement conflicted with the FOREIGN KEY constraint LINQ异常:“ INSERT语句与FOREIGN KEY约束冲突”,害怕这种关系! - LINQ Exception: “The INSERT statement conflicted with the FOREIGN KEY constraint”, afraid of the relations! INSERT语句与FOREIGN KEY约束异常冲突,但存储了数据 - The INSERT statement conflicted with the FOREIGN KEY constraint exception, but data stored SqlException: INSERT 语句与 FOREIGN KEY 约束冲突,首先使用 EF 代码 C# - SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint using EF code first C# BulkInsert:INSERT语句与FOREIGN KEY约束冲突 - BulkInsert: The INSERT statement conflicted with the FOREIGN KEY constraint “ INSERT语句与FOREIGN KEY约束冲突 - "The INSERT statement conflicted with the FOREIGN KEY constraint INSERT语句与FOREIGN KEY约束冲突 - The INSERT statement conflicted with the FOREIGN KEY constraint SqlException:INSERT语句与FOREIGN KEY约束冲突 - SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint 错误:INSERT语句与FOREIGN KEY约束冲突 - Error : INSERT statement conflicted with the FOREIGN KEY constraint INSERT语句与FOREIGN KEY约束错误冲突 - The INSERT statement conflicted with the FOREIGN KEY constraint error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM