How can I make such behaviuor in NHibernate:
There is an entity called User in my domain
// I ommit mapping attributes
public class User
{
int Id {get; set;}
int pId {get; set;}
//....other props, such as Login, Name, email...
}
I need to make full copy of it, when updating. pId must be set to original Id. Old entity must be untouched.
So this must be like some versioning system, where pId – is immutable identity, and Id – is like version. I`ve tried to use Version mapping attribute, but it just updates Version field, withou recreating full entity. What approach will be better?
I wrote a versioning system for our application. I split the versioned object into two classes, one that represents the whole object and one for its versions.
In our software, the versioning is part of the business logic. The application provides access to the history and the user has some control over the versioning.
A new version is therefore created in memory. You need to perform a deep-copy. You could implement this by implementing an interface in the root entity and all its children. This interface provides a method
DeepCopywhich is recursively called through the object graph.There is also a protected
MemberwiseCopymethod inobject, which could be helpful. It does not a deep copy.We didn’t want the pain to maintain the code which copies each single property. So we are using serialization to copy an object graph in memory:
Additionally, we have methods in the entities which reset the ids and do some other cleanup. This is also done recursively though the object graph.
For now, it works fine. In the future we probably need to refactor it to the interface implementation, which is a bit cleaner.