gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:04:48 24 4
gpt4 key购买 nike

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

  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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com