我必须在db中存储复杂对象,我已经创建了一个基类Vehicle和两个派生类Car和Truck,它继承了类Vehicle . 当我存储iam能够正确存储汽车或卡车信息,但当我检索数据时,我只能获得车辆信息,因为宇宙数据库没有存储任何类型信息,并且我使用数据类型作为车辆来检索 . 在反序列化时,cosmos db中是否有任何方法可以根据对象的属性获取派生对象 . 或者建议我在cosmosdb中存储复杂对象的任何其他方法 .
public class Vehicle
{
public string Id { get; set; }
}
public class Car : Vehicle
{
public string CarProperty { get; set; }
}
public class Truck : Vehicle
{
public string TruckProperty { get; set; }
}
文档1:
{
"id": "8e0fc57e-1886-f7bc-284c-1385a263bdfa",
"Vehicle": {
"Id ": "12314",
"CarProperty ": "b3268e04-e201-4dcf-a159-af28d5b62d4f"
}
document 2:
{
"id": "1886-f7bc-284c-1385a263bdfa-s4ws45",
"Vehicle": {
"Id": "5f37ca24-210e-43d6-b27d-d6710d70ddd3",
"TruckProperty": "e6b47210-f021-43ff-8c44-a8f09036d516"
}
我不想将JsonSerializerSettings用于TypeHandling,因为它不是推荐的 .
1 回答
您需要在基类模型上给映射器一点帮助,如下所示:
或者像这样的代码:
那你的文件应该是这样的:
生成的“_t”字段是鉴别器,用于告知存储哪种派生类型的车辆 .
我会查看驱动程序参考的Polymorphism部分 .