You are developing a C# service that manages utility smart-meter configurations using the Azure Cosmos DB .NET SDK v3. The target container is configured with a partition key path of `/gridId`.
You need to update the configuration of a specific smart meter. Your task is to write a method that retrieves the existing configuration document, changes the `ReportingIntervalMinutes` property to `15` in memory, and then saves the updated configuration back to the container.
Arrange the steps in the correct order to complete the operation.
- 1CosmosClient client = new CosmosClient(connectionString);
- 2Database database = client.GetDatabase(databaseId);
- 3Container container = database.GetContainer(containerId);
- 4ItemResponse<MeterConfig> response = await container.ReadItemAsync<MeterConfig>(meterId, new PartitionKey(gridId));
- 5MeterConfig config = response.Resource;
config.ReportingIntervalMinutes = 15; - 6await container.ReplaceItemAsync<MeterConfig>(config, meterId, new PartitionKey(gridId));
Answer
The correct order of operations starts with instantiating the CosmosClient, followed by retrieving references to the Database and Container. Next, the existing item is read using ReadItemAsync with its ID and PartitionKey. The retrieved configuration's properties are then modified in memory. Finally, the updated configuration is saved back to the container using ReplaceItemAsync, passing the modified document, its ID, and its PartitionKey.
The correct order follows the logical hierarchy of the Azure Cosmos DB .NET SDK v3. A CosmosClient must be created first to manage connections. The client is used to reference the Database, which is then used to reference the Container. Before modifying and replacing the item, the current state of the item must be read using ReadItemAsync (providing the ID and partition key). The retrieved object's properties are updated in memory next. Finally, the replacement is committed using ReplaceItemAsync with the updated object, its ID, and the partition key.
Step-by-Step Solution
Key Concept
Azure Cosmos DB .NET SDK v3 item update workflow using point read and replace