如何删除记录以及ASP.NET中的所有相关记录(C#)

时间:2014-10-07 11:22:04

标签: c# sql asp.net

我有这个代码从我的桌子上删除一个摄影师,但是,photographer_id是我桌子上的一个外键'图像'当我删除一个摄影师时我想删除&中的所有图像#39;图像'由我正在删除的摄影师的表。我怎么做?

...

else if (e.CommandName == "Slet")
{
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString =
        ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ToString();
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;

    cmd.CommandText = "DELETE FROM photographers WHERE photographer_id = @photographer_id";

    cmd.Parameters.Add("@photographer_id", SqlDbType.Int).Value = e.CommandArgument.ToString();

    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();

    Repeater1.DataBind();
}

这是我的IMAGES表:

CREATE TABLE [dbo].[images] (
    [image_id] INT  IDENTITY (1, 1) NOT NULL,
    [image] NVARCHAR (50) NOT NULL,
    [FK_photographer] INT NOT NULL,
    PRIMARY KEY CLUSTERED ([billede_id] ASC),
    CONSTRAINT [FK_fotograf] FOREIGN KEY ([FK_fotograf]) REFERENCES [dbo].[Fotografer] ([fotograf_id]),

);

这是我的摄影表:

CREATE TABLE [dbo].[photographers] (
    [photographer_id] INT IDENTITY (1, 1) NOT NULL,
    [photographer_name] NVARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED ([photographer_id] ASC)
);

4 个答案:

答案 0 :(得分:3)

在外键约束上设置cascading delete。这将自动删除图像s when you delete a摄影师。

自己不需要重新发明轮子。

答案 1 :(得分:1)

相同的方法 -

DELETE FROM images WHERE photographer_id = @photographer_id

建议先删除图像,然后删除摄影师。如果您的桌子上有物理FK,那么在您删除所有依赖项之前,它将不允许您删除摄影师。

希望这有帮助。

答案 2 :(得分:1)

正如我在评论中提到的,您可以使用级联删除。你可以改变你的表格,如下所示。

ALTER TABLE billeder
ADD CONSTRAINT fk_photographer
FOREIGN KEY (photographer_id)
REFERENCES photographers (photographer_id)
ON DELETE CASCADE;

答案 3 :(得分:0)

更好的方法是你可以在程序中完成 但这是替代和简单的方式

SqlCommand cmd = new SqlCommand();
                        cmd.Connection = conn;
    conn.Open();
    cmd.CommandText = "DELETE FROM photographers WHERE photographer_id = @photographer_id";


cmd.Parameters.Add("@photographer_id", SqlDbType.Int).Value = e.CommandArgument.ToString();


cmd.ExecuteNonQuery();
    //deleted from photographers 

cmd.CommandText = "DELETE FROM Images WHERE photographer_id = @photographer_id";


cmd.Parameters.Add("@photographer_id", SqlDbType.Int).Value = e.CommandArgument.ToString();
     cmd.ExecuteNonQuery();
    //deleted from images