If your objects are not serializable and you are just looking for a quick one-to-one copy of them, you can do this pretty easily with AutoMapper:
// define a one-to-one map
// .ForMember(x => x.ID, x => x.Ignore()) will copy the object, but reset the ID
AutoMapper.Mapper.CreateMap<MyObject, MyObject>().ForMember(x => x.ID, x => x.Ignore());
And then when you copy method:
// perform the copy
var copy = AutoMapper.Mapper.Map<MyObject, MyObject>(original);
/* make copy updates here */
// evicts everything from the current NHibernate session
mySession.Clear();
// saves the entity
mySession.Save(copy); // mySession.Merge(copy); can also work, depending on the situation
I chose this approach for my own project because I have a lot of relationships with some weird requirements surrounding record duplication, and I felt this gave me a little more control over it. Of course the actual implementation in my project varies a bit, but the basic structure pretty much follows the above pattern.
Just remember, that the Mapper.CreateMap<TSource, TDestination>()
creates a static map in memory, so it only needs to be defined once. Calling CreateMap
again for the same TSource
and TDestination
will override a map if it's already defined. Similarly, calling Mapper.Reset()
will clear all of the maps.