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

Shadowing/Hidden properties causing BsonSerializationException

    • Type: Icon: Bug Bug
    • Resolution: Works as Designed
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 2.7.3, 2.8.0
    • Component/s: Serialization
    • Labels:
      None
    • Environment:
      Windows 10 Professional x64, .NET Core 2.2

      Hi guys.
      Our project uses shadowing/hiding on inherited classes to keep backwards compatibility with older layouts of received Json files. Here are some simple example classes that reproduce the problem:

      namespace Base
      {
          public class Root
          {
              public string Id {get; set;}
              public SecondClass SecondClass {get; set;}
          }
      }
      
      namespace Base
      {
          public class SecondClass
          {
              public int Number {get; set;}        
          }
      }
      
      namespace NewVersion
      {
          public class Root : Base.Root
          {
              public new SecondClass SecondClass {get; set;}        
          }
      }
      
      namespace NewVersion
      {
          public class SecondClass : Base.SecondClass 
          {
              public string NewProperty {get; set;}        
          }
      }
      

      When I call the GetCollection method and set the type as NewVersion.Root, I'm getting a "BsonSerializationException".

      db.GetCollection<NewVersion.Root>(typeof(NewVersion.Root).Name);
      

      "MongoDB.Bson.BsonSerializationException: 'The property 'SecondClass' of type 'NewVersion.Root' cannot use element name 'SecondClass' because it is already being used by property 'SecondClass' of type 'Base.Root'.'"

      I've tried to map the classes on project startup, and the only way I found to make everything working fine is using the "SetElementName" method to change the property name to an exclusive one, however, as a side effect, these altered names will be saved on the database (as expected).
      As a workaround, I'm converting all the created objects to an ExpandoObject, removing all hidden properties, then I convert this ExpandoObject to a BsonDocument. In this case, it's not possible to use LINQ queries because the "GetCollection" method is allways typed as BsonDocument.

      I'm not sure if this is a bug or not.
      Any suggestions?
      Thanks in advance!

            Assignee:
            robert@mongodb.com Robert Stam
            Reporter:
            gabrielftz Gabriel Fetz
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: