c# - 当键是枚举时,以 "Document"表示序列化字典

标签 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)]
    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 引擎在序列化时抛出异常:

When using DictionaryRepresentation.Document key values must serialize as strings.

所以,我想也许我可以注册一个约定,让枚举序列化为字符串:

var conventions = new ConventionPack();
conventions.Add(new EnumRepresentationConvention(BsonType.String));
ConventionRegistry.Register("Custom Conventions", conventions, type => type == typeof(MyClass));

不幸的是,这似乎没有任何效果,引擎也抛出了同样的异常。

当键是枚举类型时,有什么方法可以序列化 Document 表示中的字典?

最佳答案

您可以通过显式注册一个将您的 enum 序列化为字符串的序列化程序来实现。您可以使用带有 BsonType.String 表示的内置 EnumSerializer 类:

BsonSerializer.RegisterSerializer(new EnumSerializer<MyEnum>(BsonType.String));

关于c# - 当键是枚举时,以 "Document"表示序列化字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28245530/

相关文章:

c# - Azure 队列触发器与服务总线队列触发器,我需要哪一个?

mongodb - Mongoose 文档架构和验证

c# - 试图删除涉及 int 和 long 的构造函数中的不明确调用

C# WPF - 根据背景图像动态更改文本颜色

c# - .NET Framework 2.0 与 3.5/4.0...使用旧版本有什么优势吗?

c# - SQLDataReader 如何检查空列值?

c# - 使用 MVVM 在 wpf 中使用对话框的好习惯还是坏习惯?

mongodb - Talend 数据准备 : Mongodb already installed locally on this computer

python - 使用 from_json 制作的 MongoEngine 文档对象不保存

c# - 使用 C# 在用户定义的库中实现回调