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. 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#
"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.