Question

Difficulty: EasyPerform Container and Item Operations in Azure Cosmos DB using SDK

You are developing a .NET application that stores user profiles in an Azure Cosmos DB SQL API container. The container's partition key path is set to `/userId`. You need to write C# code to create a new user profile document using the Cosmos DB .NET SDK v3. Which code segment should you use?

  1. await container.CreateItemAsync<UserProfile>(profile, new PartitionKey(profile.UserId));Answer
  2. B
    await client.CreateDocumentAsync(containerUri, profile, new RequestOptions { PartitionKey = new PartitionKey(profile.UserId) });
  3. C
    await container.CreateItemAsync<UserProfile>(profile, new PartitionKey("default"));
  4. D
    await container.CreateItemAsync<UserProfile>(profile, new PartitionKey(profile.UserId), new ItemRequestOptions { SessionToken = sessionToken });

Answer

await container.CreateItemAsync<UserProfile>(profile, new PartitionKey(profile.UserId));
The correct option correctly uses the .NET SDK v3 Container class method CreateItemAsync and provides the profile object along with a PartitionKey instance initialized with the UserId property, which aligns with the container's partition key path /userId.

Step-by-Step Solution

1
Identify the Cosmos DB SDK version required.
Cosmos DB .NET SDK v3 is required.
The scenario specifies using the .NET SDK v3, which utilizes the CosmosClient and Container classes instead of the legacy DocumentClient.
2
Determine the correct method for creating an item.
Use the CreateItemAsync method on the Container instance.
CreateItemAsync is the standard asynchronous method to insert a new item into a Cosmos DB container in SDK v3.
3
Select the correct partition key configuration matching the container's partition key path.
Pass a new PartitionKey object initialized with profile.UserId.
The partition key path is /userId. Passing a dynamic, high-cardinality value like profile.UserId ensures correct routing and avoids hot partitions.

Key Concept

Creating items asynchronously in Azure Cosmos DB using the .NET SDK v3 with a partition key.
Rate this question