Jimi
Jimi

Reputation: 1845

C#: How to store enum value as lowercase string in MongoDB

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?

Upvotes: 1

Views: 1617

Answers (1)

sobakaodin
sobakaodin

Reputation: 11

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; }

Upvotes: 1

Related Questions