Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoRepository inheritance serialization error

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.

like image 460
amcdnl Avatar asked Dec 10 '13 14:12

amcdnl


2 Answers

Adding the decorator attributes:

[BsonKnownTypes(typeof(Contractor), typeof(Employee))]

to the classes resolved the issue.

like image 196
amcdnl Avatar answered Oct 12 '22 18:10

amcdnl


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.

like image 24
bklaric Avatar answered Oct 12 '22 20:10

bklaric