When trying to combine inheritance with MongoRepository for C# I am experiencing serialization errors.
The really odd thing is it works for a short time but after say a rebuild or something it fails. If I drop the collection and create a new one it will work until a stop or rebuild.
My code looks like:
public class Organization
{
      // other attributes removed for demonstration simplicity
      public List<Person> People { get;set; }
}
public abstract class Person
{
      public string Id {get;set;}
      public string Name {get;set;}
}
public class Employee : Person 
{
      public string Badge {get;set;}
}
public class Contractor : Person
{
     public string Company {get;set;}
}
When I try to get it like:
static MongoRepository<Organization> apps = new MongoRepository<Organization>();
return apps.Single(c => c.Id == id);
The error I receive is:
An exception of type 'System.IO.FileFormatException' occurred in MongoDB.Driver.dll but was not handled in user code
Additional information: An error occurred while deserializing the People property of class API.Models.Organization: Instances of abstract classes cannot be created.
Adding the decorator attributes:
[BsonKnownTypes(typeof(Contractor), typeof(Employee))]
to the classes resolved the issue.
Had a similar problem, where Person was an abstract class inheriting from another abstract class. I disliked the idea of putting Mongo attributes in my domain model and after fiddling a bit with it, found out marking the Person class as a root makes it serialize and deserialize properly:
BsonClassMap.RegisterClassMap<Person>(cm => {
    cm.SetIsRootClass(true);
});
Note that the deserialization exception occurred because the MongoDB driver was not setting the discriminator _t field. 
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With