You are developing a C# backend service for a multi-tenant logistics application using the Azure Cosmos DB .NET SDK v3. The database contains a Shipments container configured with a partition key path of `/tenantId`.
You need to implement a method to update a shipment's delivery status with the lowest latency and cost. The method must prevent dirty writes if another thread or client instance updates the shipment concurrently.
Which of the following C# code segments should you implement to perform this update operation?
- ItemResponse<Shipment> response = await container.ReplaceItemAsync<Shipment>(
shipment,
shipment.Id,
new PartitionKey(shipment.TenantId),
new ItemRequestOptions { IfMatchEtag = shipment.ETag }
);Cevap - BItemResponse<Shipment> response = await container.ReplaceItemAsync<Shipment>(
shipment,
shipment.Id,
new PartitionKey(shipment.Status),
new ItemRequestOptions { IfMatchEtag = shipment.ETag }
); - CItemResponse<Shipment> response = await container.ReplaceItemAsync<Shipment>(
shipment,
shipment.Id,
new PartitionKey(shipment.TenantId),
new ItemRequestOptions { SessionToken = shipment.SessionToken }
); - DItemResponse<Shipment> response = await container.ReplaceItemAsync<Shipment>(
shipment,
shipment.Id,
requestOptions: new ItemRequestOptions { IfMatchEtag = shipment.ETag }
);
Cevap
The correct code segment calls ReplaceItemAsync using the shipment's TenantId as the partition key and sets the IfMatchEtag property in ItemRequestOptions to the shipment's ETag.
The correct code segment uses the Azure Cosmos DB .NET SDK v3 `ReplaceItemAsync` method to safely update the shipment. It targets the correct logical partition by passing the tenant ID as the partition key (`new PartitionKey(shipment.TenantId)`), which matches the container partition key path of `/tenantId`. It prevents dirty writes by passing the current ETag of the shipment object through the `IfMatchEtag` property in `ItemRequestOptions`. If another thread has modified the document, its ETag will have changed, causing the update to fail with a `PreconditionFailed` status code, achieving Optimistic Concurrency Control.
Adım Adım Çözüm
Anahtar Kavram
Performing safe point updates using Optimistic Concurrency Control and the correct partition key in Azure Cosmos DB .NET SDK v3.
Tahmini Süre:2m 30s