1

I'm trying to save an enum value as lowercase or with my custom representation on MongoDB using the C# driver. I already figured out how to save the enum value as string on the database, doing something like this

class MyClass
{
   ...
   [BsonRepresentation(representation: BsonType.String)]
   public MyEnum EnumValue { get; set; }
   ...
}

and the enum class is like this

[JsonConverter(converterType: typeof(StringEnumConverter))]
enum MyEnum 
{
   [EnumMember(Value = "first_value")]
   FirstValue,
   [EnumMember(Value = "second_value")]
   SecondValue
}

But on MongoDB the enum value is stored as it is in the enum class (not like what is specified in the EnumMember attribute). How can I tell MongoDB to store the enum value lowercase or with the EnumMember value?

Jimi
  • 1,605
  • 1
  • 16
  • 33

1 Answers1

1

You can create your own Serializer:

internal class LowerCaseEnumSerializer<T> : SerializerBase<T>
    where T : struct
{
    public override T Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var enumValue = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(context.Reader.ReadString());

        return Enum.Parse<T>(enumValue);
    }

    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, T value)
    {
        context.Writer.WriteString(value.ToString()?.ToLowerInvariant());
    }
}

And then use it like attribute:

[BsonSerializer(typeof(LowerCaseEnumSerializer<MyEnum>))]
public MyEnum EnumValue { get; set; }
Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
sobakaodin
  • 11
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 10 '22 at 13:34