Deletion - parent/child

Deletion - parent/child

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


fredg posted on Tuesday, February 14, 2012

Hi,

    When deleting parent, all child collections should be cleared first.

    Is there sample code to demonstrate this situation in DataPortal_DeleteSelf() of the parent BO?

    I clear the child collection in this method and then delete parent, but the child still exist in database.

JonnyBee replied on Tuesday, February 14, 2012

Hi,

I prefer to use cascading delete in the database.

There could be other relationships too, than the child objects that you have loaded into memory, so this is typically bettter handled in the database (and simpler to code).

fredg replied on Wednesday, February 15, 2012

Thanks for your reply. cascading delete in the database is a good option. However, I'm not quite understanding it in CSLA.net. If we recursively clear child collection in parent BO's delete method before deleting parent self, why not child deletion does not automatically call itself's deletion method and remove the records from database? If we want to do it in BO, what code looks like?

My code:

 

void DataPortal_DeleteSelf(Parent Parent)
{

    //clear child collection
    for (int childNumber = ChildCollection.Count() - 1; childNumber >= 0; childNumber--)
    {     
       ChildCollection.RemoveAt(childNumber);
    }

    ....delete parent....

}

 

Do you have correction for my code?

 

 

 

JonnyBee replied on Wednesday, February 15, 2012

Remove will only move the item to DeleteItems list but does not do any data access.

fredg replied on Wednesday, February 15, 2012

I see. Do you have any sample code to recommand to replace my child collection clear part's code to make data access happen?

    //clear child collection
    for (int childNumber = ChildCollection.Count() - 1; childNumber >= 0; childNumber--)
    {     
       ChildCollection.RemoveAt(childNumber);
    }

fredg replied on Thursday, February 16, 2012

Hi, can anyone provide some sample of cascading deleting children before deleting parent from BO layer instead of from DA layer?

fredg replied on Friday, February 17, 2012

After adding:

FieldManager.UpdateChildren(this);

Child's Data access code is called, but if the child table has FK constraint, there would be an error. Looks like we have to remove the FK constraint from child table.

Copyright (c) Marimer LLC