Search code examples
azurenosqlazure-cosmosdbdocument-database

Is it possible to use inheritance with CosmosDB collections?


I'm new to understanding NoSQL databases.

Suppose I have a hierarchy like

public interface MyInterface
{
    [JsonProperty("id")]
    Guid Id { get; }
}

public class Foo : MyInterface
{
    public Guid Id { get; set; }

    [JsonProperty("intVal")]
    public int IntVal { get; set; }
}

public class Bar : MyInterface
{
    public Guid Id { get; set; }

    [JsonProperty("stringVal")]
    public string StringVal { get; set; }
}

Is it possible to create a collection that holds MyInterfaces? Or can it only hold fixed Json structure and I have to do something like

public class MyClass
{
    [JsonProperty("id")]
    public Guid Id { get; set; }

    [JsonProperty("type")]
    [JsonConverter(typeof(StringEnumConverter))]
    public MyClassType Discriminator { get; set; }

    [JsonProperty("fooIntVal")]
    public int? FooIntVal { get; set; }

    [JsonProperty("barStringVal")]
    public string BarStringVal { get; set; }
}

public Enum MyClassType
{
   [JsonProperty("foo")]
   Foo,

   [JsonProperty("bar")]
   Bar
};

???


Solution

  • Is it possible to create a collection that holds MyInterfaces?

    Of course you can. As mentioned in the comments,cosmos db collections have no schema so that you could design it into any structure you want to design.

    Such as:

    {
        "id": "1",
        "Discriminator": "foo",
        "FooIntVal": 5
    },
    {
        "id": "2",
        "Discriminator": "bar",
        "BarStringVal": "aaa"
    }
    

    Or even:

    { 
        "id": "5",
        "Discriminator": {
            "foo": {
                "FooIntVal": 5
            },
            "bar": {
                "BarStringVal": "aaa"
            }
         }
    }
    

    You can adjust the data structure flexibly.I suggest you refer to this doc to get start. Any concern,please let me know.