Inheritance in MongoDb: how to request instances of defined type

By : YMC
Source: Stackoverflow.com
Question!

This is how I used to utilize inheritance in Entity Framework (POCO):

ctx.Animals // base class instances (all instances)
ctx.Animals.OfType<Cat>  // inherited class Cat's instances only
ctx.Animals.OfType<Dog> // inherited class Dog's instances only

This is the only similar way I found in MongoDb (MongoDb reference):

var query = Query.EQ("_t", "Cat");
var cursor = collection.FindAs<Animal>(query);

Note in the latter case I have to deal with discriminator ("_t") and hardcode my class name, that is not quite convenient and looks awful. If I miss the query I got an exception on enumeration attempt. Have I missed something? My suggestion was the document Db which stores objects 'as is' should handle inheritance easily.

By : YMC


Answers

From your link:

The one case where you must call RegisterClassMap yourself (even without arguments) is when you are using a polymorphic class hierarchy: in this case you must register all the known subclasses to guarantee that the discriminators get registered.


Register class maps for your base class and each one of your derived classes:

BsonClassMap.RegisterClassMap


If the only concern is hardcoding class name, you can do something like this:

collection = db.GetCollection
By : Zerdush


Take a look on the documentation http://docs.mongodb.org/ecosystem/tutorial/serialize-documents-with-the-csharp-driver/#scalar-and-hierarchical-discriminators

The main reason you might choose to use hierarchical discriminators is because it makes it possibly to query for all instances of any class in the hierarchy. For example, to read all the Cat documents we can write:

var query = Query.EQ("_t", "Cat");
var cursor = collection.FindAs
By : Noam


This video can help you solving your question :)
By: admin