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

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Closed
    • Priority: Major - P3
    • Resolution: Works as Designed
    • Affects Version/s: None
    • Fix Version/s: None
    • Component/s: Serialization
    • Labels:
      None

      Description

      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
              }
      }
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              rstam Robert Stam
              Reporter:
              peter.garafano Peter Garafano
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: