Search code examples
azureentity-framework-coreazure-cosmosdb

Dictionary property in Cosmos DB using EF


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”
    }
}

Solution

  • 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