Tepken Vannkorn
Tepken Vannkorn

Reputation: 211

INSERT statement conflicted with the FOREIGN KEY constraint

myCommand = New SqlCommand(
"INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, 
                     Price, EnterDate, CatID, RackID, Amount) 
VALUES('" & txtBookCode.Text & "','" & 
            txtTitle.Text & "','" & 
            txtAuthor.Text & "','" & 
            txtPublishYear.Text & "','" & 
            txtPrice.Text & "', #" & 
            txtEnterDate.Text & "#, " & 
            txtCategory.ValueMember & "," & 
            txtRack.ValueMember & "," & 
            txtAmount.Text & ")"
, myConnection)

The error was:

The INSERT statement conflicted with the FOREING KEY constraint "FK_tblBook_tblCategory". The conflict occurred in database "CIEDC", table "dbo.tblCategory", column 'CatID'. The statement has been terminated.

Was that because of my database's relationships?

How can this be solved?

Upvotes: 0

Views: 2187

Answers (2)

J.Doe
J.Doe

Reputation: 11

I think there are two cases:

1.

In your table dbo.tblBook, it has a column named CatID act as foreign key reference to dbo.tblCategory table. It seems that you're trying to use CatID property that haven't been created yet.if so, go back and create a CatID first.

2.

Maybe there are more than one foreign key that related to your table. if you're using sql server so below sql statement will help you find all of them, check it out and drop the leftover, good luck!

    USE <database_name>;  
GO  
SELECT   
    f.name AS foreign_key_name  
   ,OBJECT_NAME(f.parent_object_id) AS table_name  
   ,COL_NAME(fc.parent_object_id, fc.parent_column_id) AS constraint_column_name  
   ,OBJECT_NAME (f.referenced_object_id) AS referenced_object  
   ,COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS referenced_column_name  
   ,is_disabled  
   ,delete_referential_action_desc  
   ,update_referential_action_desc  
FROM sys.foreign_keys AS f  
INNER JOIN sys.foreign_key_columns AS fc   
   ON f.object_id = fc.constraint_object_id   
--WHERE f.parent_object_id = OBJECT_ID('HumanResources.Employee'); 
GO 
SELECT 
f.name AS foreign_key_name 
,OBJECT_NAME(f.parent_object_id) AS table_name 
,COL_NAME(fc.parent_object_id, fc.parent_column_id) AS constraint_column_name 
,OBJECT_NAME (f.referenced_object_id) AS referenced_object 
,COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS referenced_column_name 
,is_disabled 
,delete_referential_action_desc 
,update_referential_action_desc 
FROM sys.foreign_keys AS f 
INNER JOIN sys.foreign_key_columns AS fc 
ON f.object_id = fc.constraint_object_id 
--WHERE f.parent_object_id = OBJECT_ID('HumanResources.Employee');

Upvotes: 0

Timothy S. Van Haren
Timothy S. Van Haren

Reputation: 8966

It appears that the value of txtCategory.ValueMember does not correspond to a valid category ID in your database.

Upvotes: 2

Related Questions