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?

4
  • check this link that will help you MongoDB sorry Commented Dec 9, 2019 at 14:01
  • 1
    Ehm.... you linked my same question 😅 Commented Dec 9, 2019 at 14:03
  • 1
    check this link Commented Dec 9, 2019 at 14:04
  • Thanks, a custom serializer worked :) Commented Dec 9, 2019 at 14:49

1 Answer 1

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; }
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.