Inheritance in MongoDb: how to request instances of defined type

后端 未结 5 1801
迷失自我
迷失自我 2021-02-10 16:34

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

ctx.Animals // base class instances (all instances)
ctx.Animals.OfType  // inher         


        
5条回答
  •  盖世英雄少女心
    2021-02-10 17:28

    Well, a document db does in fact store objects "as is" - i.e. without the notion of objects belonging to some particular class. That's why you need _t when you want the deserializer to know which subclass to instantiate.

    In your case, I suggest you come up with a discriminator for each subclass, instead of relying on the class name. This way, you can rename classes etc. without worrying about a hardcoded string somewhere.

    You could do something like this:

    public abstract class SomeBaseClass
    {
        public const string FirstSubClass = "first";
        public const string SecondSubClass = "second";
    }
    
    [BsonDiscriminator(SomeBaseClass.FirstSubClass)]
    public class FirstSubClass { ... }
    

    and then

    var entireCollection = db.GetCollection("coll");
    
    var subs = entireCollection.Find(Query.Eq("_t", SomeBaseClass.FirstSubClass));
    

提交回复
热议问题