Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-1728

EnumRepresentationConvention doesn't seem to apply during serialization of Dictionary<T, U>() Where T is an Enum

    • Type: Icon: Bug Bug
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: Serialization
    • None

      Given the following example class:

      public class Test
      {
          public Dictionary<TestEnum, double> TestField { get; set; } = new Dictionary<TestEnum, double>();
      }
      
      public enum TestEnum
      {
      	A,
      	B
      }
      

      If you register an EnumRepresentationConvention using the following code and try to insert an instance of the class

      var pack = new ConventionPack { new EnumRepresentationConvention(BsonType.String) };
      ConventionRegistry.Register("EnumStringConvention", pack, t => true);
      var client = new MongoClient("mongodb://localhost/");
      var db = client.GetDatabase("test");
      var col = db.GetCollection<Test>("test");
      await col.InsertOneAsync(new Test { TestField = { { TestEnum.A, 25d } } });
      

      The last line throws a BsonSerializationException with the message:

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

      If I alter the code to include the following line anywhere before the Insert.

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

      The insert succeeds and the resulting doc in the database looks like this:

      {
              "_id" : ObjectId("5799282d945208a81ee8bfd2"),
              "TestField" : {
                      "A" : 25
              }
      }
      

            Assignee:
            robert@mongodb.com Robert Stam
            Reporter:
            peter.garafano@mongodb.com Peter Garafano (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: