.netmongodbserializationpolymorphism

Polymorphism in querying MongoDB using MongoDB.Bson in c#


I have collection in mongo DB which contains few types of documents. All of the documents contain base common properties and some extra. In C# it represent as Polymorphism:

[BsonKnownTypes(typeof(Cat), typeof(Dog))]
public class Animal
{
    public int Code;
}

[BsonKnownTypes(typeof(Lion), typeof(Tiger))]
public class Cat : Animal
{
    public string CatProperty;
}

public class Dog : Animal
{
}

public class Lion : Cat
{
}

public class Tiger : Cat
{
}

My question is: how should I implement getAnimalByCode when I don't know before what is the exact type of the animal which is going to returned. I emphasize that I want to get the entire document, not only the common properties of animal...

I saw this tutorial but I don't manage to select like this:

var collection = _database.GetCollection<Animal>("collectionName");

var myAnimal = collection.Find(animal => animal.Code == 5)
                         .FirstOrDefault();

Document with code 5 has CatProperty and the serialization failed.


Solution

  • The documents you provided in the comments lack the type discriminator. This is a property that the MongoDB C# Driver uses to determine the type of document upon deserialization in cases when polymorphism is used. By default, this property is named _t.

    The reason for the missing property is that you made the MongoDB C# Driver aware of the polymorphism and the types that can encountered in a collection with the BsonKnownTypes attribute after the documents had been stored for the first time.

    By default, the name of the type is stored in the type discriminator, e.g. Cat. If you add the _t field to the documents so that it matches the expected type of a document, you will be able to deserialize the documents to their original type in the inheritance hierarchy.

    For more information on polymorphism for MongoDB documents see this link in the docs.