While using this code to serialize an object:
public object Clone()
{
var serializer = new DataContractSerializer(GetType());
using (var ms = new System.IO.MemoryStream())
{
serializer.WriteObject(ms, this);
ms.Position = 0;
return serializer.ReadObject(ms);
}
}
I have noticed that it doesn't copy the relationships. Is there any way to make this happen?
Either annotate your classes with
[DataContract]
or add your child types in the constructor of DatacontractSerializer.To perform a deep clone you might consider using a binary serializer:
You need a binary serializer to preserve objects identity during the serialization/deserialization step.
Simply use the constructor overload that accepts
preserveObjectReferences
, and set it to true: