views:

225

answers:

2

Hi,

I just ran into a major issue for me with NHibernate. I have 2 objects, each with a collection of things. I need to move one thing from the collection from Object A to the collection of Object B. I get an error about a deleted object because, I believe, NHibernate attempts to delete the thing from the collection of Object A when it needs to keep it for Object B. From a DB standpoint, it's just a matter of updating the "parent" property to the new object (Object B). But with the collections, I am not really sure what do to...

Is there a well-known procedure to move objects from one collection into another one in NHibernate?

Thanks in advance for any help.

Regards,

Eric.

A: 

Have you tried mapping using

cascade="all-delete-orphan"

Surya
+1  A: 

I'm assuming that you are using Cascade in the mapping for the class represented by objects A and B, i.e., A and B are both instances of some class X, and X's mapping contains a cascade attribute on the collection containing the object to be transferred.

Given that assumption, this may help.

If you want to be able to transfer the object from one collection to the other, you need to consider whether the thing that is being moved should have an existence that is independent of the two collections.

If the transfer object doesn't get saved on its own, you will run into problems when you do the transfer because the transfered object is already known to the session.

There are two ways out that I can think of. The better of the two is probably to treat the transfer object as an independent object which is saved on its own to the db (i.e, doesn't rely on Cascading in the mapping of the objects with the collection). Conceptually, this makes sense because if you can transfer it from one collection to the other that implies that somehow it is independent of the two objects having the collections. It does mean that you could end up with orphans.

If you want to stick with using cascade in the mappings, then you will need to remove from object A in a different transaction than the add to object B. I suspect that isn't what you want to do.

Rob Scott
Rob, thanks for your answer. We ended up dropping NHibernate just a few days later and for some reasons, I don't remember seeing notifications of replies to my thread. Thanks anyway for your help.
Eric Liprandi