I'm working on a project where I'd like to serialize my business object to a file. I used the BinaryFormatter to serialize without problem, but I've noticed that sometimes, when my project changes,and I try to load files saved from the past, the FieldManager had stored properties differently and I receive invalid cast exceptions here (below) where it's confused as to what property info it's really trying to read. What's a work around for this problem?
protected P ReadProperty<P>(PropertyInfo<P> propertyInfo)
if (((propertyInfo.RelationshipType & RelationshipTypes.LazyLoad) == RelationshipTypes.LazyLoad) && !FieldManager.FieldExists(propertyInfo))
throw new InvalidOperationException(Resources.PropertyGetNotAllowed);
P result = default(P);
FieldManager.IFieldData data = FieldManager.GetFieldData(propertyInfo);
if (data != null)
FieldManager.IFieldData<P> fd = data as FieldManager.IFieldData<P>;
if (fd != null)
result = fd.Value;
result = (P)data.Value;
result = propertyInfo.DefaultValue;
Don't use BinaryFormatter.
This is a relatively common issue with binary formatting - version, type, and other information that's very sensitive to project changes is serialized into the binary stream. So when you do change your project, your binary-formatted stream no longer works.
If you want to save this information to a file, then you have to develop a specific format (XML is often used) that isn't version-sensitive. That requires you to write your own serialization code, but then you have control over what's serialized and how. Plus, you can deal with version changes, since you're writing the code. You can make this easier by developing a DTO-style object graph of your business objects and utilize the XML serializers in .NET to serialize/deserialize the DTO graph. Then all you have to do is get your BO data into and out of the DTO graph. That's an object-mapping exercise, which is easier to solve (and in many cases already has).
Copyright (c) Marimer LLC