4

Is there a way to with NHibernate to clone an existing object (retrieved through nhibernate) and perform an insert on it to create a new record, instead of updating the current one.

We are using this to do some kind of temporal versioning and need this kind of behavior.

Daniel Powell
  • 8,143
  • 11
  • 61
  • 108

2 Answers2

2

I am not aware of anything built into nhibernate that would do what you are after.

Warning Hack Ahead
I haven't tried this so this is just thinking out loud about how nhibernate tracks the objects.

Depending of the Object graph you could reset the version (if any) and id back to the default specified in the mapping and that should create a clone as it effectivle resets how nhibernate tracks the object and when saved it will have be given a new Id. Also note that any attached mapped objects would also need have the same done to get a deep clone.

If it was me I would probably put a clone method on the object that returns a new object with a copy of the properties, etc.

Some other answers on SO suggest using Automapper How to clone objects in NHibernate?

Community
  • 1
  • 1
Nathan Fisher
  • 7,961
  • 3
  • 47
  • 68
1

Just do a MemberwiseClone and clear the Id.

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
  • 2
    While I haven't tested this, using MemberwiseClone could lead to all sorts of problems if you're cloning a proxy object or any sort of deep nested object. It's only a shallow copy, so proxies and what not would still refer to the original entity object. – rossisdead May 01 '12 at 15:16