c# – 如何在另一个表中删除包含其父行的数据的行

有两个表[UserData]和[HotelData]我用外键链接它们.这是“用户名”,我想删除哪个用户名输入,并删除其在第二个表上的数据.我不知道如何编写sql命令或c#.

An unhandled exception of type ‘System.Data.SqlClient.SqlException’
occurred in System.Data.dll

Additional information: The DELETE statement conflicted with the
REFERENCE constraint “FKHotelData”. The conflict occurred in database
“E:\GRADED UNIT DEV\BLACKMARCH\BLACKMARCH\BIN\DEBUG\DATABASEBM.MDF”,
table “dbo.HotelData”, column ‘Username’.

该语句已终止.

private void btnDelete_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\Graded unit Dev\BlackMarch\BlackMarch\bin\Debug\DataBaseBM.mdf;Integrated Security=True;Connect Timeout=30");
    string sqlStatement = "DELETE FROM UserData WHERE Username = @Username";
    con.Open();
    SqlCommand cmd = new SqlCommand(sqlStatement, con);
    cmd.Parameters.AddWithValue("@Username", txtUsernameUser.Text);
    cmd.CommandType = CommandType.Text;
    cmd.ExecuteNonQuery();
    con.Close();
}
从UserData表中删除记录时,无需编写任何代码来删除子表上的数据.只需使用Cascade删除行为.这意味着如果删除父表中的记录,则会自动删除子表中的相应记录.

执行以下步骤:

>打开子表的设计器,然后单击“关系”
>在打开的窗口和表设计器中展开INSERT和UPDATE规范
>将删除规则从无操作更改为级联

如下图所示:

enter image description here

https://stackoverflow.com/questions/37458917/how-to-delete-a-row-with-data-with-its-parent-row-in-another-table

转载注明原文:c# – 如何在另一个表中删除包含其父行的数据的行