Dictionary property in Cosmos DB using EF

Viewed 456

I have a class as below and try to use EF core framework to store the below model to Cosmos DB. But the the JSON is stored as

{  
  "id": "e6b75f1f-0cc2-488c-9074-62e7e85c727a",
  "Type ": "testType",
  "TagName ": "TagName",
  "DictionaryList ": {}
}
public class TestDictionary
{
    public Guid Id { get; set; }
    public string Type { get; set; }
    public string TagName { get; set; }
    public Dictionary<string,object> DictionaryList { get; set; }
}

Problem is that the DictionaryList property doesn't save the data that is passed from api. It always stores as empty object instead of data passed through dictionary

I want my Jason to be stored in cosmos as below

{  
  "id": "e6b75f1f-0cc2-488c-9074-62e7e85c727a",
  "Type ": "testType",
  "TagName ": "TagName",
  "DictionaryList ": {
       “Account number”: “123456”,
    “Check date”:  “11/20/2020”
    }
}
2 Answers

Only collections of primitive types are supported by EF Core 6, So DictionaryList needs to be typed as Dictionary<string,string>

Dictionary<string,object> is recognized as a nested entity type, you could use it, but you'd need to explicitly configure all the keys that it can contain:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<TestDictionary>()
        .OwnsOne(t => t.DictionaryList, c =>
        {
            c.Property<string>("Type");
            c.Property<string>("TagName");
        });
}

I later realized that I could using the cosmos sdk insert Dictionary<stringm, object> without any problem, and that Ef core does expose the underlying cosmos client.

So I solved the issue by access the underlying cosmos client, and use that to insert my dictionary.

        var cosmosClient = dbContext.Database.GetCosmosClient();
        var container = cosmosClient.GetContainer(  "db", "container");
        await container.CreateItemAsync(new Dictionary<string,object>);

works like a charm.

remember the Id has to be id or atleast serializer has to be told that Id has to be interpreted id

Related