C# 在“中序列化词典”;文件「;表示,当键是枚举时
我正在尝试将下面的“MyClass”写入Mongo集合:C# 在“中序列化词典”;文件「;表示,当键是枚举时,c#,.net,mongodb,mongodb-.net-driver,C#,.net,Mongodb,Mongodb .net Driver,我正在尝试将下面的“MyClass”写入Mongo集合: public enum MyEnum { A, B, C }; public class MyClass { [BsonId(IdGenerator = typeof(StringObjectIdGenerator))] public string Id { get; set; } [BsonDictionaryOptions(DictionaryRepresentation.Document)] pu
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; }
}
Mongo引擎在序列化时引发异常:
使用DictionaryRepresentation时。文档键值必须序列化为字符串
所以,我想也许我可以注册一个约定,使枚举序列化为字符串:
var conventions = new ConventionPack();
conventions.Add(new EnumRepresentationConvention(BsonType.String));
ConventionRegistry.Register("Custom Conventions", conventions, type => type == typeof(MyClass));
不幸的是,这似乎没有效果,引擎抛出了相同的异常
当键是枚举类型时,有没有办法序列化文档表示中的词典?可以通过显式注册序列化程序来实现这一点,该序列化程序将
枚举
序列化为字符串。您可以将内置的EnumSerializer
类与BsonType.String
表示形式一起使用:
{
_id: "12345",
Items: {
A: {
MyProp: "foo"
},
B: {
MyProp: "bar"
},
C: {
MyProp: "baz"
},
}
}
BsonSerializer.RegisterSerializer(new EnumSerializer<MyEnum>(BsonType.String));
BsonSerializer.RegisterSerializer(新的EnumSerializer(BsonType.String));
是否仅在此特定情况下将MyEnum
序列化为字符串?还是到处都可以?@I3arnon也可以。