开发者

Entities used to serialize data have changed. How can the serialized data be upgraded for the new entities?

I have a bunch of simple entity instances that I have serialized to a file. In the future, I know that the structure of these entities (ie, maybe I will rename Name to Header or something). The thing is, I don't want to lose the data that I have saved in all these old files. What is the proper way to either

  1. load the data from the old entities into new entities
  2. upgrade the old files so that they can be used with new entities

Note: I think I am stuck with binary serialization, not xml serialization.

Thanks in advance!

Edit: So I have an answer for the ca开发者_Go百科se I have described. I can use a dataContractSerializer and do something like

[DataMember("bar")]
private string foo;

and change the name in the code and keep the same name that was used for serialization. But what about the following additional cases:

  1. The original entity has new members which can be serialized
  2. Some serialized members that were in the original entity are removed
  3. Some members have actually changed in function (suppose that the original class had a FirstName and LastName member and it has been refactored to have only a FullName member which combines the two)

To handle these, I need some sort of interpreter/translator deserialization class but I have no idea what I should use


I you have used BinaryFormatter, then note that this is a field serializer, not a property serializer; you can hack around it by not changing the field names. Unless it is an auto implemented property, in which case you can't.

To be honest, BinaryFormatter is a poor choice if you want the flexibility to mutate the types. A contract-based serializer is much more flexible here. For example, XmlSerializer and DataContractSerializer allow ou to control the names via an attribute.

If you want binary, I would go with protobuf-net (perhaps because I wrote it...) - here there are no names - just numeric identifiers. But the protobuf format was designed by Google specifically to allow painless upgrade of APIs.

Of course, you might also look at a DTO as permenant contract; in which case consider having a v1 DTO, a v2 DTO etc. Not the way I tend to do it myself, but definitely an option.


No matter what serialization mechanism you use, renaming a property is a breaking change. The problem with binary serialization is that you cannot easily upgrade the files to the new format which would be an easier task with text format serialization.


You'll need to write a program that

  • deserializes the data into the old version of the entity
  • transforms the old version of the entity into the new version of the entity
  • serializes the new version of the entity back to the file.

If you've serialized it to XML, you could probably write an XSLT to make the required changes directly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜