如何将具有外键约束的记录删除到另一个表?

时间:2015-11-04 00:37:15

标签: c# sql-server database datagridview

当我尝试从datagridview删除行时请参阅表Famille,我得到的错误是:

  

类型' System.Data.SqlClient.SqlException'未处理的异常   发生在System.Data.dll中的附加信息:DELETE   语句与REFERENCE约束冲突   " FK_NatureCharge_Famille&#34 ;.冲突发生在数据库中   " Tresorerie",table" dbo.NatureCharge",column' IdFam'。该声明   已被终止。

这个表(Famille和NatureCahrge) enter image description here
顺便说一句,Famille部分可以删除datagridview中的多行。 我试图添加删除NaturCharge 1st(它以评论删除自然开始)
代码:

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.Parameters.AddWithValue("@IdFam", row.Cells["IdFam"].Value);
                            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();
                    }
                }
            }

            //Update the datagridview
            this.BindGrid();
        }
    }

错误显示为行(它是用于Famille部分) `cmd.ExecuteNonQuery();``

  

其他信息:DELETE语句与   参考约束&#34; FK_NatureCharge_Famille&#34;。冲突发生了   在数据库&#34; Tresorerie&#34;,table&#34; dbo.NatureCharge&#34;,column&#39; IdFam&#39;。

看起来DELETE语句似乎不正确

更新代码

//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));
                }
            }

和同样的错误...

3 个答案:

答案 0 :(得分:1)

您可以使用级联删除原始表中的所有外键记录。

在某些DBMS中,它设置在外键约束的级别上,一些设置在删除本身上。

请查看以下链接以获取更多信息。

http://www.techonthenet.com/sql_server/foreign_keys/foreign_delete.php

答案 1 :(得分:1)

在这种情况下,我建议您在外键操作中使用级联删除,您可以比自己删除相关寄存器更简化代码库。

但如果您仍想自己动手,可以使用我已经动机化的这段代码

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)
                                          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
        var idsToDelete = selectedRows.Select(row => row.Cells["IdFam"].Value).ToList();
        try
        {
            using (var con = new SqlConnection(connstring))
            {
                var ids = string.Join(",", idsToDelete);
                using (var deleteNatures = new SqlCommand("DELETE FROM NatureCharge IdFam IN " + ids, con))
                using (var deleteFamilles = new SqlCommand("DELETE FROM Famille WHERE Id IN " + ids, con))
                {
                    deleteNatures.Parameters.AddWithValue("@IdFam", row.Cells["IdFam"].Value);
                    con.Open();
                    deleteNatures.ExecuteNonQuery();
                    deleteFamilles.ExecuteNonQuery();
                }

                con.Close();
            }
        }
        catch (SystemException ex)
        {
            MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
        }

        //Update the datagridview
        this.BindGrid();
    }
}

答案 2 :(得分:0)

我的解决方案: 在删除表之前,我必须删除与之相关的所有相关表。 所以我的ocde很简单,我得到的所选DataGridView的IdFam比我在NatureCharge表中删除具有相同ID的行

我的代码:

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)
            {
                int aa = Convert.ToInt32(row.Cells["IdFam"].Value);
                conn = new SqlConnection(connstring);
                conn.Open();
                comm = new SqlCommand("DELETE FROM NAtureCharge WHERE IdFam ='" + aa + "'", conn);
                try
                {
                    comm.ExecuteNonQuery();
                    //MessageBox.Show("Deleted...");
                }
                catch (Exception)
                {
                    MessageBox.Show("Not Deleted");
                }
                finally
                {
                    conn.Close();
                }
            }

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

            //Update the datagridview
            this.BindGrid();
        }
    }