Reputation: 14934
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 ?
Upvotes: 1
Views: 920
Reputation: 630
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)));
});
Upvotes: 3