简体   繁体   中英

how to read derived object from cosmos db with document db client from C#

I have to store complex object in db, i have created a base class Vehicle and two derived classes Car and Truck which inherits class Vehicle . when i store iam able to store Car or Truck info properly, but when iam retrieving the data i could get only Vehicle information because cosmos db is not having any type information stored and iam using datatype as Vehicle to retrieve. Is there any way in cosmos db to get the derived object based on the properties of object while deserializing. Or suggest me any other approach to follow for storing complex objects in 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; }
}

document1:

{
    "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"  
    }

I dont want to use JsonSerializerSettings for TypeHandling since it is not recommonded.

You need to give the mapper a little help either on the base class model like this:

[BsonDiscriminator(RootClass = true)]
[BsonKnownTypes(typeof(Car), typeof(Truck))]
public class Vehicle
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
}

or in code like this:

BsonClassMap.RegisterClassMap<Vehicle>(cm => {
    cm.AutoMap();
    cm.SetIsRootClass(true);
    cm.MapIdMember(c => c.Id);
});
BsonClassMap.RegisterClassMap<Car>();
BsonClassMap.RegisterClassMap<Truck>();

Then your documents should look like:

{
    "id": "8e0fc57e-1886-f7bc-284c-1385a263bdfa",    
    "Vehicle": {
        "_id": "5f37ca24-210e-43d6-b27d-d6710d70ddd3",
        "_t": "Car",
    "CarProperty": "Value for Car Property"
    }

The generated "_t" field is the discriminator and used tell which derived type of Vehicle is stored.

I would check out the Polymorphism section of the driver reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM