We need to move some data in string format to an enum and since the existing data does not correspond to how we want our enum to look like, I'm using a custom Serializer (in MongoDB).
My code looks something like that:
public override MyEnum Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
if (context.Reader.CurrentBsonType == MongoDB.Bson.BsonType.Null) return MyEnum.Unknown;
return ParseMyEnum(context.Reader.ReadString());
}
However, whenever I fetch a class containing MyEnum from the database, I get the above mentioned exception.
The answer is very straight forward: the reason why we get this exception is simply because we return MyEnum.Unknown without actually reading the value. The fix would be then:
if (context.Reader.CurrentBsonType == MongoDB.Bson.BsonType.Null) {
context.Reader.ReadNull();
return MyEnum.Unknown;
}
Hope this helps someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With