Soru

Zorluk: OrtaPerform Container and Item Operations in Azure Cosmos DB using SDK

You are developing a C# service that manages customer profiles in Azure Cosmos DB using the .NET SDK v3. The service must connect to the database, navigate the resource hierarchy, and update a user profile. The database is named ProfileDb, the container is named Profiles, and the partition key path for the container is /userId.

You have an existing UserProfile instance named profile that contains a UserId property.

Which sequence of C# code blocks must you execute to initialize the client and upsert the user profile?

  1. 1CosmosClient client = new CosmosClient(connectionString);
  2. 2Database database = client.GetDatabase("ProfileDb");
  3. 3Container container = database.GetContainer("Profiles");
  4. 4PartitionKey partitionKey = new PartitionKey(profile.UserId);
  5. 5await container.UpsertItemAsync<UserProfile>(profile, partitionKey);

Cevap

The correct sequence starts with initializing the CosmosClient, obtaining the database reference, getting the container reference, instantiating the PartitionKey with the partition key property value, and finally calling UpsertItemAsync.
The C# .NET SDK v3 enforces a hierarchical resource model. You must first construct the root CosmosClient. From that client, you obtain the Database reference using GetDatabase. Using the Database object, you retrieve the Container reference using GetContainer. Before modifying or adding an item, a PartitionKey object must be initialized with the corresponding value. Finally, calling UpsertItemAsync on the container with the item and its partition key completes the operation.

Adım Adım Çözüm

1
Initialize CosmosClient
A client connection to Azure Cosmos DB is established.
CosmosClient is the top-level SDK object required for all interactions.
2
Retrieve Database reference
A Database object representing ProfileDb is obtained.
Containers reside within a database context, so database access must precede container access.
3
Retrieve Container reference
A Container object representing Profiles is obtained.
Item operations are executed against a specific container.
4
Instantiate PartitionKey
A PartitionKey instance is created with the profile's UserId.
SDK v3 requires a PartitionKey object to perform point operations like UpsertItemAsync efficiently.
5
Execute UpsertItemAsync
The item is written or replaced in the container.
Calling UpsertItemAsync writes the updated data to the target partition.

Anahtar Kavram

Azure Cosmos DB .NET SDK v3 Resource Hierarchy and Item Operations
Tahmini Süre:1m 30s
Bu soruyu puanla