在"文档"中序列化字典。表示,当键是枚举时

时间:2015-01-30 22:14:43

标签: c# .net mongodb mongodb-.net-driver

我正在尝试写#34; 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?

1 个答案:

答案 0 :(得分:9)

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

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