c#-4.0 - MongoDb 中的继承 : how to request instances of defined type

标签 c#-4.0 mongodb polymorphism mongodb-.net-driver mongodb-query

这就是我过去在 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 reference ) 中发现的唯一类似方式:

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

请注意,在后一种情况下,我必须处理鉴别器(“_t”)并对我的类名进行硬编码,这不太方便而且看起来很糟糕。如果我错过了查询,我会在枚举尝试时遇到异常。我错过了什么吗?我的建议是“按原样”存储对象的文档 Db 应该可以轻松处理继承。

最佳答案

假设您的鉴别器正在运行(_t 为每个文档正确存储)那么我认为这就是您要寻找的。

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

仅返回“Cat”类型的文档。

关于c#-4.0 - MongoDb 中的继承 : how to request instances of defined type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10405887/

相关文章:

mongodb - 使用 mgo 通过输入选择查询的选定字段

c++ - C++ 中继承的重载规则

.net - "Leaking"线程句柄

javascript - 异步和等待方法

mongodb - 异常验证 MongoCredential 和未分类的 Mongo Db 异常

c++ - 当转换为父类对象而不是引用时会出现什么不良结果?

java - 简单 Java 多态性的 C++ 等价物

c# - 无法将类型 System.LinQ.IOrderedEnumerable 隐式转换为 MyClassCollection。存在隐式转换(您是否缺少强制转换?)

java - 使用 Spring 进行 MongoDB 复制