In my C# code, I have an enum type that is going to be stored in MongoDB as string. In my C# code I have this type:
public enum Color
{
Unknown =0,
Red =1,
Blue =2,
Brown =3,
}
When in MongoDB string value is Red, Blue or Brown there is no problem but sometimes in DB there are other colours that are not included in my enum type like black, in this case, I expect the Color deserialized to Unknown but I get deserializing error indicates that black is not defined. Is there any way to handle this? I can not add every colour on my side and I can not change the enum type to any other type. I'm wondering how can I deserialize it to Unknown?
you will need a custom serializer like so:
public class ColorSerializer : SerializerBase<Color>
{
public override void Serialize(BsonSerializationContext ctx, BsonSerializationArgs args, Color value)
{
ctx.Writer.WriteString(value.ToString());
}
public override Color Deserialize(BsonDeserializationContext ctx, BsonDeserializationArgs args)
{
return
ctx.Reader.CurrentBsonType switch
{
MongoDB.Bson.BsonType.String => ctx.Reader.ReadString() switch
{
"Red" => Color.Red,
"Blue" => Color.Blue,
"Brown" => Color.Brown,
_ => Color.Unknown,
},
_ => Color.Unknown,
};
}
}
register it with the serializer registry during app startup like so:
BsonSerializer.RegisterSerializer(typeof(Color), new ColorSerializer());
done!
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