2017-02-09 142 views
1

生病得到直奔point.I有兩個表:不能添加或更新子行,外鍵約束失敗

  1. 客戶信息
  2. 訂單
現在

因爲客戶可以有0或更多的順序我使用Index在這兩個表之間創建了一個關係。母公司名稱中的主鍵是主鍵,而公司名稱是索引。

  1. 我知道數據類型和大小和引擎應該是相同的。
  2. 我也知道公司名稱應該存在於父表中以便我們可以修改子表。

我已經翻了一番檢查所有的人,但我仍然得到C#中的錯誤

「不能添加或更新子行,外鍵約束失敗」

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;如果我做什麼都 預先感謝您的弊端

+0

你在'dtgCart.Rows [I] .Cells [「公司名稱」]'的調試器值檢查? –

+0

您正試圖插入'order_info',但'CustomerName'表中不存在'CompanyName',因此查詢失敗。 – CodingYoshi

+0

@CodingYoshi公司名稱是PK –

回答

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