Storing Enums as strings in MongoDB

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

    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);
    

提交回复
热议问题