Storing Enums as strings in MongoDB

后端 未结 9 1284
盖世英雄少女心
盖世英雄少女心 2020-12-08 03:50

Is there a way to store Enums as string names rather than ordinal values?

Example:

Imagine I\'ve got this enum:

public enum Gender
{
    Fema         


        
9条回答
  •  难免孤独
    2020-12-08 04:20

    The answers posted here work well for TEnum and TEnum[], however won't work with Dictionary. You could achieve this when initializing serializer using code, however I wanted to do this through attributes. I've created a flexible DictionarySerializer that can be configured with a serializer for the key and value.

    public class DictionarySerializer : DictionarySerializerBase
        where TDictionary : class, IDictionary, new()
        where KeySerializer : IBsonSerializer, new()
        where ValueSerializer : IBsonSerializer, new()
    {
        public DictionarySerializer() : base(DictionaryRepresentation.Document, new KeySerializer(), new ValueSerializer())
        {
        }
    
        protected override TDictionary CreateInstance()
        {
            return new TDictionary();
        }
    }
    
    public class EnumStringSerializer : EnumSerializer
        where TEnum : struct
    {
        public EnumStringSerializer() : base(BsonType.String) { }
    }
    

    Usage like this, where both key and value are enum types, but could be any combination of serializers:

        [BsonSerializer(typeof(DictionarySerializer<
            Dictionary, 
            EnumStringSerializer,
            EnumStringSerializer>))]
        public Dictionary FeatureSettings { get; set; }
    

提交回复
热议问题