I am testing a number of scenarios with MongoDb to see how to recover from possible data issues.
I have classes (Addresses with collection of Address) with a zipcode property in Address which was originally cast as string. I saved out multiple records of Addresses and could retrieve them all fine. like this, var allAddresses = addresses.FindAllAs();
I changed the zip code property to int and saved some records. I then changed the zip code property back to string.
When I attempt to read the collection back I get an error deserializing, as expected. var allAddresses = addresses.FindAllAs();
My goal is to be able to override the deserialization so if an field deserialization error occurs I can choose to either ignore it or apply a default value.
I have tried a custom serializer, which is not working. Any suggestions would be appreciated.
public class MyCustomSerializer : BsonBaseSerializer
{
public override object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
{
if (bsonReader.CurrentBsonType != BsonType.String)
{
return string.Empty;
}
return bsonReader.ReadString();
}
public override void Serialize(
BsonWriter bsonWriter,
Type nominalType,
object value,
IBsonSerializationOptions options)
{
bsonWriter.WriteStartDocument();
bsonWriter.WriteName("ZipCode");
bsonWriter.WriteString(value.ToString());
bsonWriter.WriteEndDocument();
}
}