I\'m trying to preserve data on two different versions of an object and not having any success with it. Can anyone tell me what I\'m doing wrong?
Version One of the
The Xml*Attribute
classes are used by XmlSerializer
, not by DataContractSerializer
. As far as I know, DataContractSerializer
doesn't have any mechanism to handle this scenario. If you can, use XmlSerializer
instead, it's much more flexible.
If this is a requirement of your application, you could add a method decorated with the OnDeserializing attribute and then implement your own logic to add missing fields to the XmlElement collection.
To preserve unknown elements of future or past versions of DataContract
s, you can implement the IExtensibleDataObject interface. Doing so will cause any unknown elements to be placed in a property called ExtensionData
which allows future re-serialization without missing data.
Example usage would be:
[DataContract(Name="Person")]
public class Person_V1 : IExtensibleDataObject
{
[DataMember(Name = "Name")]
public string Name;
[DataMember(Name = "Age")]
public int Age;
public ExtensionDataObject ExtensionData { get; set; }
}
When the Person_V2
object is deserialized to a Person_V1
object, the Weight
property is stored in ExtensionData
, and is returned to the serialized stream when it is re-serialized.