ReadBsonType can only be called if State is a Type, not when State Value

We need to move some string-formatted data into an enum, and since the existing data doesn't match what we want our enum to look like, I'm using a custom Serializer (in MongoDB).

My code looks something like this:

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 retrieve the class containing MyEnum from the database, I get the above exception.

+3


source to share


1 answer


The answer is very simple: the reason we are getting this exception is simply because we are returning MyEnum.Unknown without actually reading the value. The fix would be as follows:

if (context.Reader.CurrentBsonType == MongoDB.Bson.BsonType.Null) {
    context.Reader.ReadNull();
    return MyEnum.Unknown;
}

      



Hope this helps someone.

+4


source







All Articles