Kostassoid Kostassoid - 1 year ago 122
C# Question

Storing Enums as strings in MongoDB

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


Imagine I've got this enum:

public enum Gender

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.

Answer Source

The MongoDB .NET Driver lets you apply conventions to determine how certain mappings between CLR types and database elements are handled.

If you want this to apply to all your enums, you only have to set up conventions once per AppDomain (usually when starting your application), as opposed to adding attributes to all your types or manually map every type:

// Set up MongoDB conventions
var pack = new ConventionPack
    new EnumRepresentationConvention(BsonType.String)

ConventionRegistry.Register("EnumStringConvention", pack, t => true);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download