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 DeepCopy
which is recursively called through the object graph.
There is also a protected MemberwiseCopy
method in object
, 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:
public static T CopyDataContract<T>(T obj)
{
NetDataContractSerializer serializer = new NetDataContractSerializer();
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, obj);
stream.Position = 0;
return (T)serializer.Deserialize(stream);
}
}
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.