在 MongoDB 中将枚举存储为字符串

有没有将 Enums 存储为字符串名称而不是序号值的方法?

例如:

假设我有这个枚举:

public enum Gender
{
Female,
Male
}

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

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

它将存储在 MongoDb 数据库中,格式为{ ... “性别”: 1... }

但我更喜欢这样的东西{ ... “性别”: “男性”... }

这可能吗? 自定义映射,反射技巧,什么都行。

我的上下文: 我在 POCO 上使用强类型集合(好吧,我标记 AR 并偶尔使用多态性)。我有一个工作单元形式的数据访问抽象层。所以我没有序列化/反序列化每个对象,但是我可以(而且确实)定义一些 ClassMaps。我使用的是正式的 MongoDb 驱动程序 + 流利的 MongoDb。

47864 次浏览

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.

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

Use MemberSerializationOptionsConvention to define a convention on how an enum will be saved.

new MemberSerializationOptionsConvention(typeof(Gender), new RepresentationSerializationOptions(BsonType.String))

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

With driver 2.x I solved using a specific serializer:

BsonClassMap.RegisterClassMap<Person>(cm =>
{
cm.AutoMap();
cm.MapMember(c => c.Gender).SetSerializer(new EnumSerializer<Gender>(BsonType.String));
});

I have found that just applying Ricardo Rodriguez' answer is not sufficient in some cases to properly serialize enum values to string into MongoDb:

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


ConventionRegistry.Register("EnumStringConvention", pack, t => true);

If your data structure involves enum values being boxed into objects, the MongoDb serialization will not use the set EnumRepresentationConvention to serialize it.

Indeed, if you look at the implementation of MongoDb driver's ObjectSerializer, it will resolve the TypeCode of the boxed value (Int32 for enum values), and use that type to store your enum value in the database. So boxed enum values end up being serialized as int values. They will remain as int values when being deserialized as well.

To change this, it's possible to write a custom ObjectSerializer that will enforce the set EnumRepresentationConvention if the boxed value is an enum. Something like this:

public class ObjectSerializer : MongoDB.Bson.Serialization.Serializers.ObjectSerializer
{
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
{
var bsonWriter = context.Writer;
if (value != null && value.GetType().IsEnum)
{
var conventions = ConventionRegistry.Lookup(value.GetType());
var enumRepresentationConvention = (EnumRepresentationConvention) conventions.Conventions.FirstOrDefault(convention => convention is EnumRepresentationConvention);
if (enumRepresentationConvention != null)
{
switch (enumRepresentationConvention.Representation)
{
case BsonType.String:
value = value.ToString();
bsonWriter.WriteString(value.ToString());
return;
}
}
}


base.Serialize(context, args, value);
}
}

and then set the custom serializer as the one to use for serializing objects:

BsonSerializer.RegisterSerializer(typeof(object), new ObjectSerializer());

Doing this will ensure boxed enum values will be stored as strings just like the unboxed ones.

Keep in mind however that when deserializing your document, the boxed value will remain a string. It will not be converted back to the original enum value. If you need to convert the string back to the original enum value, a discrimination field will likely have to be added in your document so the serializer can know what is the enum type to desrialize into.

One way to do it would be to store a bson document instead of just a string, into which the discrimination field (_t) and a value field (_v) would be used to store the enum type and its string value.

The answers posted here work well for TEnum and TEnum[], however won't work with Dictionary<TEnum, object>. You could achieve this when initializing serializer using code, however I wanted to do this through attributes. I've created a flexible DictionarySerializer that can be configured with a serializer for the key and value.

public class DictionarySerializer<TDictionary, KeySerializer, ValueSerializer> : DictionarySerializerBase<TDictionary>
where TDictionary : class, IDictionary, new()
where KeySerializer : IBsonSerializer, new()
where ValueSerializer : IBsonSerializer, new()
{
public DictionarySerializer() : base(DictionaryRepresentation.Document, new KeySerializer(), new ValueSerializer())
{
}


protected override TDictionary CreateInstance()
{
return new TDictionary();
}
}


public class EnumStringSerializer<TEnum> : EnumSerializer<TEnum>
where TEnum : struct
{
public EnumStringSerializer() : base(BsonType.String) { }
}

Usage like this, where both key and value are enum types, but could be any combination of serializers:

    [BsonSerializer(typeof(DictionarySerializer<
Dictionary<FeatureToggleTypeEnum, LicenseFeatureStateEnum>,
EnumStringSerializer<FeatureToggleTypeEnum>,
EnumStringSerializer<LicenseFeatureStateEnum>>))]
public Dictionary<FeatureToggleTypeEnum, LicenseFeatureStateEnum> FeatureSettings { get; set; }

If you are using .NET Core 3.1 and above, use the latest ultra-fast Json Serializer/Deserializer from Microsoft, System.Text.Json (https://www.nuget.org/packages/System.Text.Json).

See the metrics comparison at https://medium.com/@samichkhachkhi/system-text-json-vs-newtonsoft-json-d01935068143

using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System.Text.Json.Serialization;;


public class Person
{
[JsonConverter(typeof(JsonStringEnumConverter))]  // System.Text.Json.Serialization
[BsonRepresentation(BsonType.String)]         // MongoDB.Bson.Serialization.Attributes
public Gender Gender { get; set; }
}