Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize a Dictionary in the "Document" representation, when the key is an Enum

I am attempting to write "MyClass" below to a Mongo collection:

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:

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

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?

like image 360
McGarnagle Avatar asked Jan 30 '15 22:01

McGarnagle


1 Answers

You can achieve that by explicitly registering a serializer that serializes your enum as a string. You can use the built in EnumSerializer class with a BsonType.String representation:

BsonSerializer.RegisterSerializer(new EnumSerializer<MyEnum>(BsonType.String));
like image 160
i3arnon Avatar answered Sep 25 '22 08:09

i3arnon