how to delete child object when delete parent object?

how to delete child object when delete parent object?

Old forum URL: forums.lhotka.net/forums/t/7883.aspx


zhoujg posted on Tuesday, October 27, 2009

First I write code in parent object's delete,but I don't want to modify these code on database changing.
Now I use database's cascade delete to delete child object when delete parent object on my opensource project[OpenExpressApp],but it cann't handle at some situation.
So I want to use an enetiy model to describe these relation,and delete objects by other framework.
I don't know whether anyone has do it?




JoeFallon1 replied on Wednesday, October 28, 2009

You have already discussed the two most basic options for handling this. I am not sure why you are ruling them both out. They should both work pretty easily.

1. In code of parent object you use the parentID to delete the related child records first and then you can safely delete the parent.

2. Or you can omit that step by using the database cascade delete feature which essentially does the same thing for you.

In both cases the parentID is a foregin key in the related child record. Database changes should not affect the simple delete statement for the child records.

I guess you should explain why this straightforward relationship does not work for you.

Joe

 

zhoujg replied on Wednesday, October 28, 2009

1.1 The immediate approach directly deletes an object’s data from the database without first loading the object into memory:
if parent has child, and child has child,then it need to write code in parent object's delete to delete all child objects.I think each object should be with responsibility for delete own child.

1.2 The deferred approach requires that the object is loaded into memory:
If it can straightforward delete by parent-child relationship,this way  reduce its efficiency.

2.1 sqlserver cann't allow you to define cascade delete in self reference
2.2 a root object's a,a has child a1,a1 has child a11,other root object's b,b has child b1,b1 has child b11. b's lookup object's a, and b1's lookup object's b1. if relation aa1,bb1,ab and a1b1 all are cascade delete,sql server cause errors "may cause cycles or multiple cascade paths"

My English's very poor,so I do not know if I am made myself clear :)

JoeFallon1 replied on Thursday, October 29, 2009

OK. You have explained the complex case well enough.

I have a root BO that takes 12 delete statements to remove all of its child and related records. I coded this in a separate command class which I can then call from any BO that needs to use it. It obviously starts at the lowest level and works backwards up the hierarchy until the root is finally deleted. It uses the key at each level to remove related records. This seems like the best way to handle a complex delete to me. The code is centralized and can be used by various parts of the app that allow the root BO to be deleted.

Joe

 

Copyright (c) Marimer LLC