Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB serialize Dictionary<MyEnum,object>

I have model with some Dictionary<MyEnum, object>. When I try to insert in mongoDB with the C# driver, an exception occure with the following message :

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

Of course, I can add the attribute [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfArrays)] and it work, but I want to be able to persist the enum as string.

public MyEnum {
  A,
  B
}

[BsonDictionaryOptions(DictionaryRepresentation.Document)]
public Dictionary<MyEnum, object> MyData { get; set; }

I want to have Something like that in mongo for different reasons.

{
   "MyData": {
      "B": "xxxx",
      "A": "xxxx"
   }
}

for a single enum, I just can use the [BsonRepresentation(BsonType.String)] attribute, but how to tell to the driver for a dictionary to serialize the enum key as string?

like image 728
Demonia Avatar asked May 02 '16 17:05

Demonia


1 Answers

The problem is that the dictionary serializer does not force the key to be a string type. To get around this create a serializer of your own and select it using BsonSerializer attribute.

public class EnumDictionarySerializer<TKey, TDictionary> : DictionarySerializerBase<TDictionary> 
    where TKey : struct, Enum
    where TDictionary : class, IDictionary, new()
{
    public EnumDictionarySerializer():base(DictionaryRepresentation.Document, new EnumSerializer<TKey>(BsonType.String), new ObjectSerializer())
    {

    }

    protected override TDictionary CreateInstance()
    {
        return new TDictionary();
    }
}
like image 146
Hugh.walsh Avatar answered Sep 21 '22 03:09

Hugh.walsh