Is there a way to store Enums as string names rather than ordinal values?
Example:
Imagine I've got this enum:
public enum Gender
{
Female,
Male
}
Now if some imaginary User exists with
...
Gender gender = Gender.Male;
...
it'll be stored in MongoDb database as { ... "Gender" : 1 ... }
but i'd prefer something like this { ... "Gender" : "Male" ... }
Is this possible? Custom mapping, reflection tricks, whatever.
My context: I use strongly typed collections over POCO (well, I mark ARs and use polymorphism occasionally). I've got a thin data access abstraction layer in a form of Unit Of Work. So I'm not serializing/deserializing each object but I can (and do) define some ClassMaps. I use official MongoDb driver + fluent-mongodb.
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; }
}