简体   繁体   English

当键是枚举时,在“文档”表示中序列化词典

[英]Serialize a Dictionary in the “Document” representation, when the key is an Enum

I am attempting to write "MyClass" below to a Mongo collection: 我试图在下面写一个Mongo集合中的“MyClass”:

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

I'd like to serialize this as a document, because that is the most concise representation: 我想将其序列化为文档,因为这是最简洁的表示:

{
    _id: "12345",
    Items: {
        A: {
            MyProp: "foo"   
        },
        B: {
            MyProp: "bar"   
        },
        C: {
            MyProp: "baz"   
        },
    }
}

The Mongo engine throws an exception on serialization: Mongo引擎在序列化时引发异常:

When using DictionaryRepresentation.Document key values must serialize as strings. 使用DictionaryRepresentation.Document时,键值必须序列化为字符串。

So, I thought that maybe I could register a convention to make enums serialize as strings: 所以,我想也许我可以注册一个约定来使枚举序列化为字符串:

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

Unfortunately, this seems to have no effect, and the engine throws the same exception. 不幸的是,这似乎没有任何影响,引擎抛出相同的异常。

Is there any way to serialize a Dictionary in the Document representation, when the key is an enum type? 当密钥是枚举类型时,有没有办法在Document表示中序列化Dictionary?

You can achieve that by explicitly registering a serializer that serializes your enum as a string. 您可以通过显式注册将enum序列化为字符串的序列化程序来实现。 You can use the built in EnumSerializer class with a BsonType.String representation: 您可以将内置的EnumSerializer类与BsonType.String表示一起使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM