Recurse SaveEntity with child collections

Posts   
 
    
solidstore
User
Posts: 12
Joined: 11-Jul-2005
# Posted on: 27-May-2009 12:34:53   

Is there any way when saving an updated entity that contains a child entity collection of getting existing rows to be automatically deleted if they dont exist in the collection when save is called?

At the moment, rows are being updated and insert correctly in the child collection, but not deleted from the database if not present in the object.

I'm building the entity objects programmaticly, they haven't been fetched from the database.

Walaa avatar
Walaa
Support Team
Posts: 14993
Joined: 21-Aug-2005
# Posted on: 27-May-2009 15:50:55   

If the entities you want to delete frm the database were already in the collection and you removed them progamatically, then maybe you need to use a UnitOfWork as your transaction container, to delete them from the database. Or use the Tracking entity remove actions

Otherwise you should manually issue a deleteMulti or deleteEntitiesDirectly call to delete these entities based on some filter. Or just delete them all and insert whatever is in the collection.

rdhatch
User
Posts: 198
Joined: 03-Nov-2007
# Posted on: 27-May-2009 18:01:01   

Yes, as Walla said - if you want to do In-Memory Delete, and have the removed children be deleted when you save - you need to use RemovedEntityTrackers.

It's quite simple:

myCustomer.Orders.RemovedEntitiesTracker = New OrderCollection
myCustomer.Orders.Remove(myOrderToDelete)

Dim myWork as New UnitOfWork
myWork.AddForSave(myCustomer, True)
myWork.AddCollectionForDelete(myCustomer.Orders.RemovedEntitiesTracker)
myWork.Commit()

Hope this helps!

Ryan

PS. Remember, if you delete multiple EntityTypes within the same Unit of Work- you must add them to the UnitOfWork in the proper order (children first, then parents) to avoid SQL dependency errors.

I've written a DeleteTracker class that tracks all RemovedEntitiesTracker Collections across n-Level child entity relationships. When saving your UnitOfWork you simply call myDeleteTracker.SaveWith(myWork); which will automatically detect all dependencies (even though your entities are no longer part of an EntityGraph), determines proper commit order, and deletes inside the Unit of Work. This way, I support in-memory deletes (which, of course, can be cancelled by the user)... and I don't have to worry about the order in which to commit. I don't even need to know the specifics about how deep down into the EntityGraph the user deleted entities. It just works.