Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in MongoDb: how to request instances of defined type

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.

like image 908
YMC Avatar asked Dec 04 '22 16:12

YMC


1 Answers

Assuming your discriminators are functioning (_t is stored correctly for each document) then I think this is what you are looking for.

var results = collection.AsQueryable<Animal>().OfType<Cat>

Returns only those documents that are of type 'Cat'.

like image 79
Bob Banks Avatar answered Jan 30 '23 02:01

Bob Banks