Storing Enums as strings in MongoDB

后端 未结 9 1177
盖世英雄少女心
盖世英雄少女心 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:24

    You can customize the class map for the class that contains the enum and specify that the member be represented by a string. This will handle both the serialization and deserialization of the enum.

    if (!MongoDB.Bson.Serialization.BsonClassMap.IsClassMapRegistered(typeof(Person)))
          {
            MongoDB.Bson.Serialization.BsonClassMap.RegisterClassMap<Person>(cm =>
             {
               cm.AutoMap();
               cm.GetMemberMap(c => c.Gender).SetRepresentation(BsonType.String);
    
             });
          }
    

    I am still looking for a way to specify that enums be globally represented as strings, but this is the method that I am currently using.

    0 讨论(0)
  • 2020-12-08 04:34

    I ended up assigning values to enum items, as suggested by Chris Smith in a comment:

    I'd avoid it. The string value takes up way more space than an integer. I would however, if persistence is involved give deterministic values to each item in your enum so Female = 1, Male = 2 so if the enum is added to later or the order of items changed that you don't end up with problems.

    Not exactly what I was looking for but it seems there's no other way around.

    0 讨论(0)
  • 2020-12-08 04:35
    using MongoDB.Bson;
    using MongoDB.Bson.Serialization.Attributes;
    
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    
    public class Person
    {
        [JsonConverter(typeof(StringEnumConverter))]  // JSON.Net
        [BsonRepresentation(BsonType.String)]         // Mongo
        public Gender Gender { get; set; }
    }
    
    0 讨论(0)
提交回复
热议问题