private async Task ValidateAndSave() { if (_currentIndex != null) { // Validate var hasErrors = false; if (!_hasId) { _messages.AddLast($"Parameter guid[{_currentIndex}] is not provided."); hasErrors = true; } for (var i = 0; i < _files.Length; i++) { if (_files[i] == null) { _messages.AddLast($"Parameter file{i + 1}[{_currentIndex}] is not provided."); hasErrors = true; } } // Write to DB if (hasErrors) { // Remove created files foreach (var filename in _files) { if (filename == null) { continue; } try { _fileStore.Delete(filename); } catch (Exception ex) { _logger.LogError(ex.Message); } } _messages.AddLast($"Skipping object [{_currentIndex}]. See _messages above to get more information."); } else { try { var a = _aContext.A.Find(_id); if (a == null) // A with the same id does not exist in the DB { await _aContext.A.AddAsync(new A(_id, _files[0], _files[1], _files[2])); } else // A with the same id already exists in the DB { a.File1 = _files[0]; a.File2 = _files[1]; a.File3 = _files[2]; _messages.AddLast($"Object with id = {_id} was already presented in the databse and will be overwritten."); } await _aContext.SaveChangesAsync(); } catch (Exception ex) { _messages.AddLast($"An error occured when saving [{_currentIndex}], id = {_id}. The object was not saved to the database."); _logger.LogError(ex.Message); } } // Reset state _hasId = false; _id = Guid.Empty; for (var i = 0; i < _files.Length; i++) { _files[i] = null; } } }