Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 322
nieve Avatar asked Apr 19 '17 18:04

nieve


1 Answers

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.

like image 151
nieve Avatar answered Sep 29 '22 01:09

nieve