MongoDb中的继承:如何请求已定义类型的实例 [英] Inheritance in MongoDb: how to request instances of defined type
问题描述
这是我过去在实体框架(POCO)中利用继承的方式:
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
这是我在MongoDb中找到的唯一类似方法( MongoDb参考):
This is the only similar way I found in MongoDb (MongoDb reference):
var query = Query.EQ("_t", "Cat");
var cursor = collection.FindAs<Animal>(query);
请注意,在后一种情况下,我必须处理鉴别符("_t")并硬编码我的类名,这不太方便,而且看起来很糟糕.如果我错过查询,则会在尝试枚举时遇到异常.我错过了什么吗?我的建议是文档Db,它按原样"存储对象,应该很容易处理继承.
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.
推荐答案
假设您的鉴别功能正常(每个文档的_t存储正确),那么我认为这就是您要寻找的.
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'.
这篇关于MongoDb中的继承:如何请求已定义类型的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!