Delete parent (root) when last child deleted.

Delete parent (root) when last child deleted.

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


Phil S posted on Monday, January 16, 2012

Hello,

Using CSLA 3.8.1 here.

I'm trying to work out how to accomplish the following.  I think I've just been looking at it too long, maybe someone here can point me in the right direction.

I have an editable root object, with a child collection, populated with child objects.. nothing special so far.

When the last child object is deleted, the root object should also be deleted.

So...when a developer uses my classes they end up with code like this:

(assume that there is only 1 item in the Details collection here)

Dim obj as TheRoot = TheRoot.Fetch(keyValue)
obj.Details.Remove(obj.Details(0)) 
obj.Save()
obj = TheRoot.Fetch(keyValue)  <-- should return nothing (or blow up with "not found" exception) because the root has been deleted.

Thanks

Phil

JonnyBee replied on Monday, January 16, 2012

Hi,

I'd argue that this should be handled by your Save logic.

Ie: override the Save method on obj and if

- obj.Detalis.Count == 0 and ((Core.IEditableCollection)obj.Details).GetDeletedList().Count > 0
        then call obj.MarkDeleted()
              before calling  base.Save()

You could also add code in an override of OnChildChanged but what if the user deletes all children and then add 1 or more new child objects.
Would it be OK if the object has already been marked as Deleted?

Phil S replied on Monday, January 16, 2012

Overriding Save looks like the ticket.   Thanks, this'll work nicely

I was trying to work out how to this in the dataportal_xyz methods of the root but it seemed like i was going down the wrong path.

 

Phil S replied on Tuesday, January 17, 2012

Just in case anyone needs this in VB.Net

Public Overrides Function Save() As rootClass
  If Me.Details.Count = 0 Then
    'if no details left
    If DirectCast(DirectCast(Me.Details, Csla.Core.IEditableCollection).GetDeletedList, Csla.Core.MobileList(Of MyChildClass)).Count > 0 Then
      'and we deleted at least one of the detail items...
     'make sure the root object is tagged for deletion.
      Me.MarkDeleted()
    End If
 End If
Return MyBase.Save()
End Function

Copyright (c) Marimer LLC