Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing NHibernate to cascade delete before inserts

Tags:

I have a parent object which has a one-to-many relationship with an ISet of child objects. The child objects have a unique constraint (PageNum and ContentID - the foreign key to the parent).

<set name="Pages" inverse="true" cascade="all-delete-orphan" access="field.camelcase-underscore">     <key column="ContentId" />     <one-to-many class="DeveloperFusion.Domain.Entities.ContentPage, DeveloperFusion.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> </set> 

The problem I've hit is if I remove a ContentPage element from the parent collection, and then add a new one with the same unique key within the same transaction... You get a unique constraint violation because NHibernate attempts to perform the insert before the delete.

Is there a way to force NHibernate to perform the delete first?

like image 790
James Crowley Avatar asked Apr 01 '09 17:04

James Crowley


2 Answers

There is no option to specify the order of operations in a transaction as it is hard-coded as follows (from the documentation):

The SQL statements are issued in the following order

  • all entity insertions, in the same order the corresponding objects were saved using ISession.Save()
  • all entity updates
  • all collection deletions
  • all collection element deletions, updates and insertions
  • all collection insertions
  • all entity deletions, in the same order the corresponding objects were deleted using ISession.Delete()

(An exception is that objects using native ID generation are inserted when they are saved.)

As such, can I challenge you to answer why you are adding a new entity with an existing identifier? An identifier is supposed to be unique to a specific "entity." If that entity is gone, so should be its identifier.

Another option would be to do an update on that record instead of a delete/insert. This keeps the ID the same so there is no unique constraint violation (on the key at least) and you can change all the other data so that it's a "new" record.

EDIT: So apparently I wasn't entirely paying attention to the question when I responded since this is a problem with a unique constraint on a non-primary-key column.

I think you have two solutions to choose from:

  1. Call Session.Flush() after your delete which will execute all the changes to the session up to that point, after which you can continue with the rest (inserting your new object). This works inside of a transaction as well so you don't need to worry about atomicity.
  2. Create a ReplacePage function which updates the existing entity with new data but keeps the primary-key and the unique column the same.
like image 79
Stuart Childs Avatar answered Sep 21 '22 13:09

Stuart Childs


I am experiencing the same problem ... I have an entity which has a collection that is mapped to a table which contains a unique constraint.

What I do not understand is, that according to Stuarts reply, collection deletions should occur before collection inserts? When I dive into the NHibernate sourcecode, I find the CollectionUpdateAction class, which contains this code in its Execute method:

persister.DeleteRows(collection, id, session); persister.UpdateRows(collection, id, session); persister.InsertRows(collection, id, session); 

Then, I would assume that deletes are executed before inserts, but apparently this is not the case. Is the CollectionUpdateAction not used in this scenario? When is the CollectionUpdateAction used?

Answer:

I have worked around this like this:

  • In my mapping, I've set the cascade option to 'delete-orphan' instead of 'all-delete-orphan'
  • All my database access goes via a repository; in the save method of my repository, I have this code for my entity:

    public void Save( Order orderObj ) {     // Only starts a transaction when there is no transaction     // associated yet with the session    With.Transaction(session, delegate()    {        session.SaveOrUpdate (orderObj);        session.Flush();         foreach( OrderLine line in orderObj.Lines )        {             session.SaveOrUpdate (line);        }     };  } 

So, I save the orderObj, and because the cascade is set to delete-orphan, objects that are to be deleted, will be deleted from the database.

After I call SaveOrUpdate, I must make sure to flush the changes to the database.

Since the delete-orphan cascade setting makes sure that no OrderLines are inserted or updated, I have to loop over my collection, and call 'SaveOrUpdate' for each OrderLine. This will make sure that new OrderLines will be inserted, and modified ones are updated. No action will be performed for OrderLines that have not changed.

Although it is not the ideal solution (it's an ugly hack IMHO), it kind of works, and it is abstracted away behind the repository, so this is how I deal with this problem for now...

like image 26
Frederik Gheysels Avatar answered Sep 20 '22 13:09

Frederik Gheysels