1

I want to retrieve one item from Cosmos DB and there must be a better way than what I am doing here.

I've tried other commands, but this seems to actually work.

    public async Task<ToDoItem> GetAsync(string id)
    {
        FeedIterator<ToDoItem> results = container.GetItemQueryIterator<ToDoItem>("select top 1 * from Items i where i.id = '" + id + "'");

        FeedResponse<ToDoItem> item = await results.ReadNextAsync();

        return item.Resource.FirstOrDefault();
    }

I expect to be able to do this with one line that executes on the server and doesn't force me to look at a set of items.

2 Answers2

1

Here is an example from the official document to query,

 using (ResponseMessage responseMessage = await container.ReadItemStreamAsync(
                partitionKey: new PartitionKey("Account1"),
                id: "SalesOrder1"))
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

The SDK is still in development - this may help:

using (ResponseMessage response = await _container.ReadItemStreamAsync(id: pageId, partitionKey: partitionKey))
{
    if (!response.IsSuccessStatusCode)
    {
        //Handle and log exception
    }

    await using (Stream stream = response.Content)
    {
        using (var streamReader = new StreamReader(stream))
        {
            string content = streamReader.ReadToEnd();
        }
    }
}
mariana
  • 13
  • 5