Reputation: 102783
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?
Upvotes: 9
Views: 4041
Reputation: 116596
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));
Upvotes: 14