简体   繁体   中英

How to map a nullable enum to string in Mongo C# client

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM