0

I have a collection in MongoDB which I'm trying to "FindAndModify" using C# driver. This collection holds types of a base class and its derived classed, as follows:

    [BsonDiscriminator(RootClass = true)]
    public class Father
    {
        public Guid Id { get; private set; }
    }

   public class Son : Father
   {
        public string SomeProperty { get; private set; }
   }

When I'm trying to cast the BsonDocument to my base class, after the FindAndModify, where the result is "Son":

Father modifiedDocument = result.GetModifiedDocumentAs<Father>();

I get the following exception:

System.IO.FileFormatException: Element 'SomeProperty' does not match any field or property of class Father.

Any idea why? -Can't I perform a down cast here?

Thanks, Nir.

nirpi
  • 715
  • 1
  • 9
  • 24

1 Answers1

0

I was able to solve this issue by registering the class map of the "Son" type on load. Here's a reference to the code I'm using:

    if (!BsonClassMap.IsClassMapRegistered(typeof(T)))
    {
        BsonClassMap.RegisterClassMap<T>
        (cm =>
        {
            cm.AutoMap();
        });
    } 

Hope this helps someone.

Cheers, Nir.

nirpi
  • 715
  • 1
  • 9
  • 24