Updating a JSON item

In this part of the demo, we are going to update a Family item. Therefore, add the following code:

  1. Copy and paste the ReplaceFamilyItemAsync method after your QueryItemsAsync method:
   private async Task ReplaceFamilyItemAsync()
{
ItemResponse<Family> PacktPubFamilyResponse = await this.container.ReadItemAsync<Family>("PacktPub.1", new PartitionKey("PacktPub"));
var itemBody = PacktPubFamilyResponse.Resource;

// update registration status from false to true
itemBody.IsRegistered = true;
// update grade of child
itemBody.Children[0].Grade = 6;

// replace the item with the updated content
PacktPubFamilyResponse = await this.container.ReplaceItemAsync<Family>(itemBody, itemBody.Id, new PartitionKey(itemBody.LastName));
Console.WriteLine("Updated Family [{0},{1}]. Body is now: {2} ", itemBody.LastName, itemBody.Id, PacktPubFamilyResponse.Resource);
}
  1. Then, add a call to ReplaceFamilyItemAsync in the GetStartedDemoAsync method:
 public async Task GetStartedDemoAsync()
{
// Create a new instance of the Cosmos Client
this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
await this.CreateDatabaseAsync();
await this.CreateContainerAsync();
await this.AddItemsToContainerAsync();
await this.QueryItemsAsync();

//ADD THIS PART TO YOUR CODE
await this.ReplaceFamilyItemAsync();
}
  1. Run the application, and you will see that the Family item is being updated.

In this part of the demonstration, we updated an item in the container. In the next part, we will delete an item from the container.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.39.60