How to make EF core 6 correctly store derived types with Cosmos DB provider?

Viewed 151

I have an entity

public class MyEntity
{
  public string Id {get; set;}
  public ObjectNode Node;
}

ObjectNode is the base class for specific nodes:

public class ObjectNode
{
  public string NodeType {get; set;}
  public string Id { get; set; }
}

Then, there are various subclasses of ObjectNode, for example:

public class DocumentNode : ObjectNode
{
  public string Path { get; set;}
}

I configure: modelBuilder.HasDefaultContainer("MyEntity");

I create a MyEntity instance like this:

var ent = new MyEntity {
  Id = "entity1",
  Node = new DocumentNode {
      Id = "node1",
      NodeType = "Document"
      Path = "some document path"
  }
};

When storing it in Cosmos DB, the result is:

{
  "Id" : "entity1",
  "Node" : {
      "Id" : "node1",
      "NodeType" : "Document"
   }
  ]
}

The Path property doesn't show up and when deserializing, I'm getting back an ObjectNode instead of a DocumentNode.

Only by changing NodeType Node to Document Node in my model, would I get all properties. But obviously then it won't work for other derived types.

How can this behavior be fixed? I tried to declare DocumentNode as an entity using modelBuilder.Entity<DocumentNode>, but that yields a runtime error about a missing partition key property - which is right, as I don't want this to be stored as a separate document but just as a nested element.

0 Answers
Related