Inheritance in MongoDb: how to request instances of defined type

后端 未结 5 1947
时光说笑
时光说笑 2021-02-10 16:41

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:06

    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();
    BsonClassMap.RegisterClassMap();
    BsonClassMap.RegisterClassMap();
    

    Make sure that your collection is of type of your base class:

    collection = db.GetCollection("Animals");
    

    Find using your query. The conversion to the corresponding child class is done automatically:

    var query = Query.EQ("_t", "Cat");
    var cursor = collection.Find(query);
    

提交回复
热议问题