The INSERT statement conflicted with the FOREIGN KEY C#

Asked

Viewed 6,778 times

2

I have this code to insert values into a table:

conn.Open();
comm.CommandText = @"INSERT INTO ArticleBarCode(Code, Code_Article, BarCode, CreatedBy, CreatedOn, ModifiedBy, ModifiedOn, IsDeleted)
                   VALUES (@code, @codearticle, @barcode, 1, @date, 1, @date, 0)";
comm.Parameters.AddWithValue("@code", next);
comm.Parameters.AddWithValue("@codearticle", code);
comm.Parameters.AddWithValue("@barcode", numbercode);
comm.Parameters.AddWithValue("@date", DateTime.Now);
comm.ExecuteNonQuery();
conn.Close();

But when I run it gives me this mistake:

The INSERT statement conflicted with the FOREIGN KEY Constraint "Fk_articlebarcode_article". The Conflict occurred in database "Cardozugestdb", table "dbo. Article", column 'Code'.

How can I fix this ?

1 answer

4

Well, the mistake says you’re violating the constraint of the foreign key by entering a value that does not exist in the reference table. In other words, the value that is passing to the column Code does not exist in the table Article.

You have to see your model to say for sure what the field is, because your insert just doesn’t say exactly. If you have doubt of the field review the contraint Fk_articlebarcode_article.

  • How can I fix it then ?

  • inserting values that exist in the Article table. validate the values to make sure that it is an existing value

Browser other questions tagged

You are not signed in. Login or sign up in order to post.