Lee Simpson
Lee Simpson

Reputation: 309

Best practice to serialize and deserialize .net objects across versions

Objects are serialized to a database using the .NET XML serializer. The object can change over time, and therefore multiple versions exist in the database at one time.

Any suggestions for the best way to construct your code, so that you can still deserialize this object into the latest version. (interfaces / maps / manual serialization etc.)

Upvotes: 5

Views: 3078

Answers (5)

Pontus Gagge
Pontus Gagge

Reputation: 17278

This all depends on your application. Is it a distributed rich application where old applications may encounter new data objects from a central database or other source? (Much like older versions of office applications need to have some ways of dealing with newer document formats.)

If so, custom serialization and deserialization with explicit schema version numbering, I'd say. I'd put explicit metadata on each element and attribute, stating whether a reader must understand the element/attribute (and default values if not). This can of course consume quite a lot of space and increase code complexity...

But the answer really depends on why you are serializing to a database. You're not interested in using the database for its relational capabiities? Otherwise, an O/R mapping solution might be of interest.

Upvotes: 1

Nicolas Dorier
Nicolas Dorier

Reputation: 7475

Look here this talk about best practices on WCF datacontract versioning, this is a bit more specific than what you really want, but these patterns solve the same problem as yours, you can use them in any technology you want.

Upvotes: 2

James L
James L

Reputation: 16874

Have a schema version number in the serialized object. Using custom deserialization, check the version attribute first, and if it turns out to be an old version, upgrade it to the latest schema before deserializing.

Upvotes: 2

RvdK
RvdK

Reputation: 19800

What Alex Reitbort tells.

You can also implement the ISerializable interface to handle old value's

Upvotes: 0

Alex Reitbort
Alex Reitbort

Reputation: 13706

Don't remove/rename properties. Only add them.

Assign default values to all properties.

This will guarantee that xml serializer will be able to deserialize old xml into new object, and that object will have "sane" values.

Upvotes: 0

Related Questions