/// <summary> /// Deletes the items from the database. /// </summary> /// <param name="serviceProvider">The application service provider.</param> /// <param name="token">The cancellation token for the task.</param> public async Task DeleteAsync(IServiceProvider serviceProvider, CancellationToken token) { // Check if there weren't any valid items found. if (Items == null) { // Throw an exception. throw new TaskException("No valid items could be found with the provided data."); } // Get the total number of batches. var count = Math.Ceiling((double)Items.Count() / ApplicationDbContext.BatchSize); // Go over each batch. for (var index = 0; index < count; index++) { // Check if the cancellation was requested. if (token.IsCancellationRequested) { // Break. break; } // Get the items in the current batch. var batchItems = Items .Skip(index * ApplicationDbContext.BatchSize) .Take(ApplicationDbContext.BatchSize); // Get the IDs of the items in the current batch. var batchIds = batchItems.Select(item => item.Id); // Define the list of items to get. var databases = new List <Database>(); // Use a new scope. using (var scope = serviceProvider.CreateScope()) { // Use a new context instance. using var context = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>(); // Get the items with the provided IDs. var items = context.Databases .Where(item => batchIds.Contains(item.Id)); // Check if there were no items found. if (items == null || !items.Any()) { // Continue. continue; } // Get the items found. databases = items .ToList(); } // Get the IDs of the items. var databaseIds = databases .Select(item => item.Id); // Delete the dependent entities. await DatabaseExtensions.DeleteDependentSamplesAsync(databaseIds, serviceProvider, token); await DatabaseExtensions.DeleteDependentDatabaseEdgeFieldsAsync(databaseIds, serviceProvider, token); await DatabaseExtensions.DeleteDependentDatabaseNodeFieldsAsync(databaseIds, serviceProvider, token); // Delete the related entities. await DatabaseExtensions.DeleteRelatedEntitiesAsync <DatabaseUserInvitation>(databaseIds, serviceProvider, token); await DatabaseExtensions.DeleteRelatedEntitiesAsync <DatabaseUser>(databaseIds, serviceProvider, token); // Delete the items. await IEnumerableExtensions.DeleteAsync(databases, serviceProvider, token); } }