An enterprise hotel management application uses Azure Cosmos DB to store reservation details. The container uses the guest's ID (guestId) as the partition key. You are writing a C# helper method using the Azure Cosmos DB .NET SDK v3 that retrieves an existing booking, modifies the check-out date, and saves the changes back to the database.
Which sequence of code statements must you execute to complete these tasks?
- 1CosmosClient client = new CosmosClient(connectionString);
- 2Database database = client.GetDatabase(databaseId);
- 3Container container = database.GetContainer(containerId);
- 4ItemResponse<Booking> response = await container.ReadItemAsync<Booking>(bookingId, new PartitionKey(guestId));
- 5response.Resource.CheckOutDate = newCheckOutDate;
- 6await container.ReplaceItemAsync<Booking>(response.Resource, bookingId, new PartitionKey(guestId));
Answer
Initialize the CosmosClient, obtain references to the database and container, execute ReadItemAsync to fetch the booking, modify the checkout date property, and call ReplaceItemAsync with the updated object and partition key.
To update an existing item in Azure Cosmos DB using the .NET SDK v3, you must first initialize a CosmosClient and drill down to the Container reference. From there, you perform a point read using ReadItemAsync to fetch the item, which requires the item ID and the PartitionKey. After modifying the deserialized object exposed via the Resource property of the response, you call ReplaceItemAsync, again specifying the updated object, the item ID, and the PartitionKey to save the changes.
Step-by-Step Solution
Key Concept
Performing point read and replacement operations on items using the Cosmos DB .NET SDK v3.