简体   繁体   中英

Delete parent and child records without using on delete cascade

So, let's we go to the point. I have a project that where the user can delete the records from the database, but of course if I delete the parent record, I will get an error because it has child records in another table. So, what I want to do is I want to delete the parent records, and when I delete it, all the rows in child records that include the parents key or primary key will be deleted as well without using cascade.

Here is the code for example :

if (row != -1)
        {
            tbl_employee.Rows.RemoveAt(row);

            int id = Convert.ToInt32(txt_employeeid.Text.ToString());
            employee emp = db.employees.Single(x => x.employeeid == id);
            db.employees.DeleteOnSubmit(emp);
db.SubmitChanges();
        }
        else
        {
            MessageBox.Show("Click the row first!");

        }

But, I have an error The DELETE statement conflicted with the REFERENCE constraint . I know I can use on delete cascade , but is there any other thing for delete the child records without using it?

Using Cascade Delete would be the simplest, but I agree its not a good solution since you have no control over which child tables may be deleted and which may not.

So you have 2 options left :

  1. Delete the rows in the child tables in your client before deleting the master (in the same transaction off course)
  2. Delete the rows in the child tables (and the master table row) in an instead of trigger

The latter has the advantage that it is done on the database side again, and like the other solutions also gives you control which tables may be deleted and which do not.
You can even put some extra checks in there if you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM