I'm working on a C# application that uses a MySQL Database. I'm trying to insert into one table with 2 foreign keys, but am getting an error:
Cannot add or update a child row: a foreign key constraint fails (thedatabase
.tblC
, CONSTRAINT tblC_ibfk_1
FOREIGN KEY (ID
) REFERENCES tblA
(ID
) ON DELETE NO ACTION ON UPDATE CASCADE)
The table structure is
tblA - ID, col2, col3, col4...
tblB - ID, col2, col3, col4...
tblC - tblA.ID, tblB.ID, col3, col4, col5...
I've been looking over the forums, and for the life of me I can't find the syntax to make it work.
Here is what I'm using to connect. I've confirmed that the ID's to exist in the parent tables.
//Connect to the database
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand cmd;
connection.Open();
//Insert new record into database
cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO tblC(tblA_ID, tblB_ID, col3, col4, col5) VALUES(@tblA_ID, @tblB_ID, @col3, @col4, @col5);";
cmd.Parameters.AddWithValue("@tblA_ID", tblA_ID);
cmd.Parameters.AddWithValue("@tblB_ID", tblB_ID);
cmd.Parameters.AddWithValue("@col3", col3);
cmd.Parameters.AddWithValue("@col4", col4);
cmd.Parameters.AddWithValue("@col5", col5);
cmd.ExecuteNonQuery();
connection.Close();