使用Ado.net进行级联删除

时间:2013-06-19 12:54:59

标签: sql sql-server ado.net cascade cascading-deletes

我有一个应用程序需要从表Client

中删除一行
public void Delete_Client(int _id_client)
        {
            Data.Connect();
            using (Data.connexion)
            {
                string s = "Delete From CLIENT where id_client = " + _id_client;
                SqlCommand command = new SqlCommand(s, Data.connexion);
                try
                {
                    command.ExecuteNonQuery();
                }
                catch { }
            }
        }

Client包含对另一个表的外部引用。因此,出现异常表示删除必须是级联。

那么如何更改我的代码来执行此操作(我使用sql server作为dbms)?

1 个答案:

答案 0 :(得分:1)

IMO你应该避免使用on delete cascade因为:

  1. 你失控了被删除的内容
  2. 必须更改表引用才能启用它
  3. 使用参数化查询(作为所有建议)
  4. 所以我们改变你的查询。我添加了ClientOrder作为示例表,其中包含对我们即将被删除的客户端的外键引用。 首先,我删除链接到客户端的所有订单,然后删除客户端本身。对于所有其他表格,这应该是这样的 与Client表链接的链接。

    public void Delete_Client(int _id_client)
    {
        Data.Connect();
    
        using (Data.connexion)
        {
            string query = "delete from ClientOrder where id_client = @clientId; delete From CLIENT where id_client = @clientid";
    
            SqlCommand command = new SqlCommand(query, Data.connexion);
            command.Parameters.AddWithValue("@clientId", _id_client);
    
            try
            {
                command.ExecuteNonQuery();
            }
            catch { } //silencing errors is wrong, if something goes wrong you should handle it 
        }
    }
    

    参数化查询有许多优点。首先它更安全(看看SQL注入攻击)。第二种类型是通过框架解决的(特别有助于格式化DateTime

相关问题