[英]Delete foreign Key
我试图删除表 NatureCharge 中引用 Famille 表主键的外键,因为我需要删除 Famille 中的多行
对于删除多行,它有效,但在 NatureCharge 中删除行的问题表看起来像这样
编码 :
private void DeleteFamBtn_Click(object sender, EventArgs e)
{
List<DataGridViewRow> selectedRows = (from row in DataGridViewFamille.Rows.Cast<DataGridViewRow>()
where Convert.ToBoolean(row.Cells["checkBoxColumn"].Value) == true
select row).ToList();
if (MessageBox.Show(string.Format("Do you want to delete {0} rows?", selectedRows.Count), "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//delete Nature de Charge before delete Famille
foreach (DataGridViewRow row in selectedRows)
{
try
{
using (SqlConnection con = new SqlConnection(connstring))
{
con.Open();
using (SqlCommand command = new SqlCommand("DELETE NatureCharge FROM NatureCharge n INNER JOIN Famille f on n.IdFam = f.IdFam WHERE IdNat = @IdNat", con))
{
command.ExecuteNonQuery();
}
con.Close();
}
}
catch (SystemException ex)
{
MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
}
}
//Delete Famille
foreach (DataGridViewRow row in selectedRows)
{
using (SqlConnection con = new SqlConnection(connstring))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM Famille WHERE IdFam = @IdFam", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@IdFam", row.Cells["IdFam"].Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
错误显示与线(它是 Famille 部分)
cmd.ExecuteNonQuery();
附加信息:DELETE 语句与 REFERENCE 约束“FK_NatureCharge_Famille”冲突。 冲突发生在数据库“Tresorerie”、表“dbo.NatureCharge”、“IdFam”列中。
您忘记在此处添加@IdNat
参数:
using (SqlCommand command = new SqlCommand("DELETE NatureCharge FROM NatureCharge n INNER JOIN Famille f on n.IdFam = f.IdFam WHERE IdNat = @IdNat", con))
{
// you haven't added the @IdNat parameter
command.ExecuteNonQuery();
}
如果您整理了代码,这一点会更加明显。
string sql = "DELETE NatureCharge
FROM NatureCharge n
INNER JOIN Famille f on n.IdFam = f.IdFam
WHERE IdNat = @IdNat";
^^^^^^
using (SqlCommand command = new SqlCommand(sql, con))
{
// you haven't added the @IdNat parameter
command.ExecuteNonQuery();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.