Monday, November 26, 2007

SubSonic Updated Templates to Delete Entities With Children

In a recent project that I worked on I had a need to delete a top entity that had multiple children. With the generated code out of the box from SubSonic I found it difficult to delete the parent entity and all the children that depend on the parent entity since I had to specifically invoke the child entity for a delete operation. So I decided to mess with the templates. In particular with the 'Controller' (CS_ODSController.aspx).

I decided to create a method named "DeleteWithChildren()" that will take the primary key id of the parent entity to follow the same controller pattern already in place similar methods.

DeleteWithChildren() will go load the parent entity using the primary key and then invoke the corresponding controller class for each of each children.

For example,

public void DeleteWithChildren(object keyID)

// Load the entity
MyCompany.Model.Employee entity = new MyCompany.Model.Employee(keyID);

foreach(MyCompany.Model.SiteEmployee child in entity.SiteEmployeeRecords)




This allowed me to simple invoke the parent entity controller such as Controller.ParentEntity.DeleteWithChildren(5000); and have the controller delete everything the hangs off the ParentEntity object by calling the DeleteWithChildren() method for each child. This allows to delete hierarchical entities.

You can download the template file from my online box here.

My template was code to first check that a transaction was started since you might not want to attempt to delete everything from that entity without a transaction.

No comments:

Post a Comment