简体   繁体   中英

Cannot add or update a child row: a foreign key constraint fails

ill get straight to the point.I have two tables:

  1. Customer info
  2. Orders

now since a customer can have 0 or more order I created a relation between these two tables using Index. In parent table company name is Primary key and in order company name is index.

  1. I know that the data types and size and engines should be the same.
  2. I also know that the company name should exist in parent table in order that we can modify the child table.

I've doubled checked all of them but i still get the error in c#

"Cannot add or update a child row: a foreign key constraint fails"

for (int i = 0; i < dtgCart.Rows.Count; i++)
{
    command.CommandText = "INSERT INTO order_info (CompanyName,Order_ID,ProductName,Model,Address,Quantity,Price) VALUES(@CompanyName,@Order_ID,@ProductName,@Model,@Address,@Quantity,@Price)";
    command.Parameters.AddWithValue("@CompanyName",dtgCart.Rows[i].Cells["CompanyName"]);
    command.Parameters.AddWithValue("@Order_ID", dtgCart.Rows[i].Cells["Order_ID"]);
    command.Parameters.AddWithValue("@ProductName", dtgCart.Rows[i].Cells["ProductName"]);
    command.Parameters.AddWithValue("@Model", dtgCart.Rows[i].Cells["Model"]);
    command.Parameters.AddWithValue("@Address", dtgCart.Rows[i].Cells["Address"]);
    command.Parameters.AddWithValue("@Quantity",dtgCart.Rows[i].Cells["Quantity"]);
    command.Parameters.AddWithValue("@Price",dtgCart.Rows[i].Cells["Price"]);
    command.ExecuteNonQuery();
}
Con.Close(); 
Con.Dispose();

this is the code that insert data to the child table

关系设计器视图

should i use SET FOREIGN_KEY_CHECKS=0; if i do what are the drawbacks thank you in advance

This code Works Now

      for (int i = 0; i < dtgCart.Rows.Count-1; i++)
      {
command.CommandText = "INSERT INTO order_info (CompanyName,Order_ID,ProductName,Model,Address,Quantity,Price) VALUES(@CompanyName,@Order_ID,@ProductName,@Model,@Address,@Quantity,@Price)";
command.Parameters.AddWithValue("@CompanyName",dtgCart.Rows[i].Cells["CompanyName"].Value);
command.Parameters.AddWithValue("@Order_ID", dtgCart.Rows[i].Cells["Order_ID"].Value);
command.Parameters.AddWithValue("@ProductName", dtgCart.Rows[i].Cells["ProductName"].Value);
command.Parameters.AddWithValue("@Model", dtgCart.Rows[i].Cells["Model"].Value);
command.Parameters.AddWithValue("@Address", dtgCart.Rows[i].Cells["Address"].Value);
           command.Parameters.AddWithValue("@Quantity",dtgCart.Rows[i].Cells["Quantity"].Value);
command.Parameters.AddWithValue("@Price",dtgCart.Rows[i].Cells["Price"].value);
command.ExecuteNonQuery();
    }
  Con.Close(); 
            Con.Dispose();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM