c# - 无法添加或更新子行 : a foreign key constraint fails

标签 c# mysql foreign-keys primary-key

我开门见山了。我有两个表:

  1. 客户信息
  2. 订单

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

  1. 我知道数据类型和大小以及引擎应该相同。
  2. 我也知道公司名称应该存在于父表中,以便我们可以修改子表。

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

这是向子表插入数据的代码

Relation Designer view

我应该使用 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();

关于c# - 无法添加或更新子行 : a foreign key constraint fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42148881/

相关文章:

mysql - 如何在cakephp2中使用mysql函数

mysql - 将外键添加到新创建的表(mySQL)时出错

c# - Winforms图表: how to enable background color gauge

c# - 使用 C# 计算 Lat Long 是否在一个国家/地区内

c# - 尝试打开互斥量时出现 UnauthorizedAccessException

c# - 无法使用 Google Calendar API 加载 System.Threading.Tasks 程序集

php - 如何按组中的其他列排序?

mysql - SQL Select SUM() 组函数使用无效

mysql - 外键关系在 mysql 中不起作用

c# - EntityFramework Code First 1对1数据添加