Nhibernate clone object and insert as new record

Is there a way with NHibernate to clone an existing object (obtained via nhibernate) and paste on it to create a new record instead of updating the current one.

We use this to do some kind of temporary version control and we need this behavior.

+4
source share
2 answers

I do not know anything built into nhibernate that will do what you need.

Burglar Warning
I have not tried this, so this is just thinking out loud about how nhibernate is tracking objects.

Depending on the graph of the object, you could reset the version (if any) and id to return to the default specified in the mapping, and this should create a clone, since it allows you to reset how nhibernate tracks the object, and when it is saved, it will have get a new identifier. Also note that any attached mapped objects would also have to do the same in order to get a deep clone.

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

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

+2
source

Just run MemberwiseClone and clear the id.

+1
source

Source: https://habr.com/ru/post/1379064/


All Articles