public async Task SaveBulkAsync <T>(List <T> items) where T : MasterDocument { if (items?.Count <= 0) { new ArgumentNullException(nameof(items)); } var firstItem = items.First(); if (firstItem.Id.IsNullOrEmpty()) { throw new ArgumentNullException($"First item {nameof(firstItem.Id)}.", items.GetType().Name); } var partitionId = firstItem.Id.IdToMasterPartitionId(); foreach (var item in items) { item.PartitionId = partitionId; item.SetDataType(); await item.ValidateObjectAsync(); } double totalRU = 0; try { var partitionKey = new Cosmos.PartitionKey(partitionId); var concurrentTasks = new List <Task>(items.Count); foreach (var item in items) { concurrentTasks.Add(container.UpsertItemAsync(item, partitionKey) .ContinueWith(async(responseTask) => { if (responseTask.Exception != null) { logger.Error(responseTask.Exception); } totalRU += (await responseTask).RequestCharge; })); } await Task.WhenAll(concurrentTasks); } catch (Exception ex) { throw new CosmosDataException(partitionId, ex); } finally { logger.Metric($"CosmosDB RU, @master - save bulk count '{items.Count}' type '{typeof(T)}'.", totalRU); } }
public async Task UpsertItemAsync(string id, T item) { await _container.UpsertItemAsync <T>(item, ResolvePartitionKey(id)); }