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?
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With