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

BsonConstructorAttribute doesn't seem to behave as expected with named parameters

    • Type: Icon: Bug Bug
    • Resolution: Done
    • Priority: Icon: Minor - P4 Minor - P4
    • 2.4
    • Affects Version/s: 2.2.4
    • Component/s: BSON, Serialization
    • Labels:
      None

      Documentation suggests here would suggest that it's possible to map a constructor's parameters to various members by specifying them in overloads of the BsonConstructorAttribute.

      As far as I can tell, this attribute has only one overload, which takes a sequence of strings. Assuming that these strings are supposed to be the names of the members to map to, this does not appear to be working as intended.

      The following class will not serialise:

      public class Product
              {
                  public int Id { get; private set; }
      
                  [BsonIgnoreIfNull]
                  public string Name { get; private set; }
      
                  [BsonIgnoreIfNull]
                  public int OtherField { get; private set; }
      
                  [BsonConstructor("Id","Name")]
                  public Product(int id, string val)
                  {
                      Id = id;
                      Name = val;
                  }
      
                  [BsonConstructor("Id","OtherField")]
                  public Product(int id, int val)
                  {
                      Id = id;
                      OtherField = val;
                  }
              }
      

      The following which follows the default naming convention does work however:

      public class Product
              {
                  public int Id { get; private set; }
      
                  [BsonIgnoreIfNull]
                  public string Name { get; private set; }
      
                  [BsonIgnoreIfNull]
                  public int OtherField { get; private set; }
                  
                  [BsonConstructor]
                  public Product(int id, string name)
                  {
                      Id = id;
                      Name = name;
                  }
                  
                  [BsonConstructor]
                  public Product(int id, int otherField)
                  {
                      Id = id;
                      OtherField = otherField;
                  }
              }
      

            Assignee:
            robert@mongodb.com Robert Stam
            Reporter:
            TKilFre Tristan Kilani-Freeman [X]
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: