Search code examples
c#asp.net-coreasp.net-web-apiazure-cosmosdbazure-cosmosdb-sqlapi

ReadItemAsync Cosmos DB


I have a cosmos db container with below fields (id,Category,Type). The partition key is Category. While using the Below query I need to pass Partition key also. But I have only ID value. How do I perform the operation using ReadItemAsync?. I am getting not found error.

private async Task<T> GetItem(string id)
        {
            
                ItemResponse<T> response = await this.MainContainer.ReadItemAsync<T>(id, new PartitionKey(id));
                return response.Resource;
         }

Solution

  • If you do not know the partition key value, you can use GetItemQueryable instead:

    public T GetItemAsync(string id)
    {
        IQueryable<T> queryable = container.GetItemLinqQueryable<T>(true);
        queryable = queryable.Where<T>(item => item.Id == id);
        return queryable.ToArray().FirstOrDefault();
    }