We are working on an application where we have to create copies of a whole object graph and save this copy as a new object(or better an object tree) to the database.
I found 2 possible solutions to get this done:
Option 1 – Serialize and deserialize the object tree
This is probably the easiest solution. Take the object tree you want to copy, serialize it, deserialize it and attach it to an NHibernate session. The only caveat is that every object in your object tree should be marked as [Serializable].
Option 2 – Combining an ID reset, Session.Evict and some dependency walking
Another option is to walk through the object tree yourself while resetting the id values to their default. Don’t forget to remove the objects from the session first by calling Session.Evict.