我在 mongo DB 中有一些集合,其中包含几种类型的文档。 所有文档都包含基本的公共属性和一些额外的属性。 在 C# 中,它表示为多态性:
[BsonKnownTypes(typeof(Cat), typeof(Dog))]
public class Animal
{
public int Code;
}
[BsonKnownTypes(typeof(Lion), typeof(Tiger))]
public class Cat : Animal
{
public string CatProperty;
}
public class Dog : Animal
{
}
public class Lion : Cat
{
}
public class Tiger : Cat
{
}
我的问题是:当我之前不知道要返回的 Animal 的确切类型是什么时,我应该如何实现“getAnimalByCode”。我强调一下,我要获取整个文档,而不仅仅是Animal的共同属性...
我看到了这个教程,但我无法像这样选择:
var collection = _database.GetCollection<Animal>("collectionName");
var myAnimal = collection.Find(animal => animal.Code == 5).FisrOrDefault();
代码为 5 的文档具有 CatProperty 并且序列化失败。
您在评论中提供的文档缺少 类型鉴别器。在使用多态性的情况下,MongoDB C# 驱动程序使用此属性来确定反序列化时的文档类型。默认情况下,此属性名为
_t
。
缺少属性的原因是,在第一次存储文档后,您让 MongoDB C# 驱动程序了解多态性以及具有
BsonKnownTypes
属性的集合中可能遇到的类型。
默认情况下,类型名称存储在类型鉴别器中,例如
Cat
。如果将 _t
字段添加到文档中,使其与文档的预期类型匹配,您将能够将文档反序列化为其在继承层次结构中的原始类型。
有关 MongoDB 文档多态性的更多信息,请参阅文档中的link。