1

I've a document with a nullable enum like this:

public enum Gender
{
    Male,
    Female
}

public class Person {
    public Gender? Gender { get; set;}
}

I'm using MongoDB C# Driver and has mapped the enum to be serialize as a string:

BsonClassMap.RegisterClassMap<Person>(map =>
{
    map.AutoMap();
    map.SetIgnoreExtraElements(true);
    map.MapMember(x => x.Gender).SetSerializer(new EnumSerializer<Gender>(BsonType.String);
});

This works fine for non-nullable types, but failed for this nullable enum:

Value type of serializer is Gender and does not match member type System.Nullable`1[[Gender]]. (Parameter 'serializer')

How can I map a nullable enum to a string ?

3
  • check this solution from MongoDB driver Commented Dec 1, 2021 at 11:25
  • Or this would help : github.com/mongodb/mongo-csharp-driver/blob/master/src/… Commented Dec 1, 2021 at 14:32
  • You can fix that by setting a DefaultValue attribute on the property, e.g. [DefaultValue(MyEnumType.Default)] Commented Dec 1, 2021 at 19:29

1 Answer 1

3

There is a special wrapper just for your case - NullableSerializer<T>. Use it like this:

BsonClassMap.RegisterClassMap<Person>(map =>
{
    map.AutoMap();
    map.SetIgnoreExtraElements(true);
    map.MapMember(x => x.Gender).SetSerializer(new NullableSerializer<Gender>(new EnumSerializer<Gender>(BsonType.String)));
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply. What are the pros and cons using this SetSerializer method vs. using ConventionRegistry and the EnumRepresentationConvention posted above? Except that the first is for each map member whereas the other is on a global level.

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.