无法添加或更新 child 行:外键约束失败

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

我会直接进入 point.I 有两个 table:

  1. 客户信息
  2. 订单

现在,由于客户可以有 0 个或多个订单,我使用索引在这两个 table 之间创建了一个关系。在parent table 公司名称是主键和顺序公司名称是索引。

  1. 我知道数据类型和大小和引擎应该是一样的。
  2. 我也知道公司名称应该在parenttable中,以便我们修改childtable。

我已经仔细检查了所有这些,但我仍然在 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();

这是向 child table

插入数据的代码

我应该使用 SET FOREIGN_KEY_CHECKS=0;如果我这样做有什么缺点 提前谢谢你

此代码现在可用

      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();