You are developing a C# service that processes patient health telemetry using the Azure Cosmos DB .NET SDK v3. The container's partition key is `/patientId`, and the database is configured with Session consistency.
You need to write code to create a patient profile and their first telemetry entry atomically in a single transaction. Then, a separate background processing service (instantiated as a different CosmosClient) must read the newly created profile with guaranteed read-your-writes consistency.
Which two of the following code segments must you implement to achieve this?
- TransactionalBatchResponse response = await container.CreateTransactionalBatch(new PartitionKey(patientId))
.CreateItem<PatientProfile>(profile)
.CreateItem<TelemetryLog>(log)
.ExecuteAsync();Cevap - string sessionToken = response.Headers.Session;
ItemRequestOptions options = new ItemRequestOptions { SessionToken = sessionToken };
ItemResponse<PatientProfile> readResponse = await backgroundContainer.ReadItemAsync<PatientProfile>(
profile.Id,
new PartitionKey(patientId),
options
);Cevap - CTransactionalBatchResponse response = await container.CreateTransactionalBatch(new PartitionKey(profile.HospitalRegion))
.CreateItem<PatientProfile>(profile)
.CreateItem<TelemetryLog>(log)
.ExecuteAsync(); - DItemResponse<PatientProfile> readResponse = await backgroundContainer.ReadItemAsync<PatientProfile>(
profile.Id,
new PartitionKey(patientId)
);
Cevap
To perform the atomic transaction and read the written data with read-your-writes guarantees across different client sessions, you must create a transactional batch using the patient's partition key and then capture and pass the session token to the reader client.
The transactional batch must be created using the partition key (patientId) on the container instance. To guarantee read-your-writes consistency across separate CosmosClient sessions, the session token must be explicitly retrieved from the write response headers and passed in the ItemRequestOptions of the read request.
Adım Adım Çözüm
Anahtar Kavram
Cosmos DB Transactional Batching and Session Consistency Sharing