我有此代碼從我的表中刪除攝影師,但是,photographer_id是我的表'圖像'的外鍵,當我刪除一位攝影師,我想刪除我正在刪除的攝影師在「圖像」表中的所有圖像。我怎麼做?如何刪除記錄以及所有相關記錄在ASP.NET(C#)
...
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();
}
這是我的圖片表:
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)
);
您可以添加級聯刪除或首先檢查照片表並首先刪除照片。 – christiandev 2014-10-07 11:24:54
請注意,您可以(也應該)通過[使用「使用」](http://www.hanselman.com/blog/WhyTheUsingStatementIsBetterThanASharpStickInTheEyeAndASqlConnectionRefactoringExample.aspx)來改進您的代碼。 – BCdotWEB 2014-10-07 11:29:26