I have a parent entity with a collection of children entities that need to be updated from a webservice pretty much every time I access that parent entity. I figured I could just do a Clear() on the collection and then add the list of entities I receive from the web service. It seems to work fine when the entities I receive do not have the same Id as any of the ones I just cleared but if any of the Ids are the same I get the NonUniqueObjectException. Since I am clearing them shouldn't they be deleted before the new entities are inserted? Why does it matter if the Ids are the same?
preguntado el 25 de abril de 13 a las 00:04
Even though your IDs are the same, the objects themselves are not actually the same. You can verify this by doing yourobject. GetHashCode() in the watch.
NHibernate thinks that this is a new database object and wants to insert it.
You need to keep the original object and copy the new values into it.
You can copy these values manually, property by property - but I would recommend making this dynamic, so that you dont need a method for every object type.
You can write your own dynamic method with reflection or use a third party mapper... Try AutoMapper https://github.com/AutoMapper/AutoMapper
Be careful when copying the properties accross. If your chil objects have any further children which are also mapped, you will run into the same problem again.
After clear method, save parent object. so it removes children from database and session. then add children and save once again.
After the initial deletion of children objects with a clear() I had to do a flush() before re inserting the new children (that may have the same Ids). Then I did a save and everything worked.