首页 > 数据库 > 数据库开发技术 > Mongo当键是枚举时,以“文档”表示序列化字典
首先我们要先了解一下MongoDB中有什么样的数据类型:
Object ID :Documents 自生成的 _id
String:字符串,必须是utf-8
Boolean:布尔值,true 或者false (这里有坑哦~在我们大Python中 True False 首字母大写)
Integer:整数 (Int32 Int64 你们就知道有个Int就行了,一般我们用Int32)
Double:浮点数 (没有float类型,所有小数都是Double)
Arrays:数组或者列表,多个值存储到一个键 (list哦,大Python中的List哦)
Object:如果你学过Python的话,那么这个概念特别好理解,就是Python中的字典,这个数据类型就是字典
Null:空数据类型 , 一个特殊的概念,None Null
Timestamp:时间戳
Date:存储当前日期或时间unix时间格式 (我们一般不用这个Date类型,时间戳可以秒杀一切时间类型)
尝试将下面的“MyClass”写入 Mongo 集合:
public enum MyEnum { A, B, C };
public class MyClass
{
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
public string Id { get; set; }
[BsonDictionaryOptions(DictionaryRepresentation.Document)]
public Dictionary<MyEnum , MyOtherClass> Items { get; set; }
}
public class MyOtherClass
{
public string MyProp { get; set; }
}
将其序列化为文档,这是最简洁的表示:
{
_id: "12345",
Items: {
A: {
MyProp: "foo"
},
B: {
MyProp: "bar"
},
C: {
MyProp: "baz"
},
}
}
Mongo 引擎在序列化时抛出异常:使用 DictionaryRepresentation.Document 时,键值必须序列化为字符串。所以,我想也许我可以注册一个约定来使枚举序列化为字符串:
var conventions = new ConventionPack();
conventions.Add(new EnumRepresentationConvention(BsonType.String));
ConventionRegistry.Register("Custom Conventions", conventions, type => type == typeof(MyClass));
不幸的是,这似乎没有效果,引擎抛出了同样的异常。当键是枚举类型时,有什么方法可以在 Document 表示中序列化 Dictionary 吗?可以通过显式注册将您的序列化为enum字符串的序列化程序来实现这一点。可以使用EnumSerializer带有BsonType.String表示的内置类:
BsonSerializer.RegisterSerializer(new EnumSerializer<MyEnum>(BsonType.String));
原文作者:后端Q;如有侵权,请联系管理员删除。