将Enums作为字符串存储在MongoDB中 [英] Storing Enums as strings in MongoDB

查看:798
本文介绍了将Enums作为字符串存储在MongoDB中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以将Enums存储为字符串名称而不是顺序值?

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

示例:

想象一下我有这个枚举:

Imagine I've got this enum:

public enum Gender
{
    Female,
    Male
}

现在,如果某些虚构的用户存在

Now if some imaginary User exists with

...
Gender gender = Gender.Male;
...

它将以{..."Gender":1 ...}的形式存储在MongoDb数据库中

it'll be stored in MongoDb database as { ... "Gender" : 1 ... }

但是我更喜欢这样的东西{..."Gender":"Male" ...}

but i'd prefer something like this { ... "Gender" : "Male" ... }

这可能吗?自定义映射,反射技巧等等.

Is this possible? Custom mapping, reflection tricks, whatever.

我的情况:我在POCO上使用了强类型的集合(嗯,我标记了AR,并偶尔使用了多态性).我以工作单元的形式有一个薄的数据访问抽象层.因此,我不对每个对象进行序列化/反序列化,但可以(并且确实)定义一些ClassMap.我使用官方的MongoDb驱动程序+ fluent-mongodb.

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.

推荐答案

MongoDB .NET驱动程序

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

如果您希望将其应用于所有枚举,则只需为每个AppDomain设置一次约定(通常是在启动应用程序时),而不是向所有类型添加属性或手动映射每种类型:

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

这篇关于将Enums作为字符串存储在MongoDB中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆