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?
- 1CosmosClient client = new CosmosClient(connectionString);
- 2Database database = client.GetDatabase("ProfileDb");
- 3Container container = database.GetContainer("Profiles");
- 4PartitionKey partitionKey = new PartitionKey(profile.UserId);
- 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
Anahtar Kavram
Azure Cosmos DB .NET SDK v3 Resource Hierarchy and Item Operations
Tahmini Süre:1m 30s