[英]Cannot add or update a child row: a foreign key constraint fails
ill get straight to the point.I have two tables: 生病直截了当。我有两张桌子:
now since a customer can have 0 or more order I created a relation between these two tables using Index. 既然客户可以有0个或更多订单,我使用Index在这两个表之间创建了一个关系。 In parent table company name is Primary key and in order company name is index.
在父表中,公司名称是主键,公司名称是索引。
I've doubled checked all of them but i still get the error in c# 我加倍检查所有这些但我仍然在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; 我应该使用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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.