public async Task SaveAsync(RequestList model) { var isFirstLoadConfig = _configuration["Environment:IS_FIRST_LOAD"] ?? Environment.GetEnvironmentVariable("IS_FIRST_LOAD") ?? "false"; bool.TryParse(isFirstLoadConfig, out var isFirstLoad); if (isFirstLoad) { var entitiesToAdd = model.requests.ToEntities <RequestEntity, Request>(); await _requestEntityRepository.AddManyAsync(entitiesToAdd); return; } var requestIds = model.requests.Select(x => x.RequestId).ToList(); var alreadySavedRequests = (await _requestEntityRepository.FindAsync(x => requestIds.Contains(x.RequestId))) .Select(x => (x.EntityId, x.RequestId)) .ToDictionary(x => x.RequestId, x => x.EntityId); var requestsToUpdate = model.requests.Where(x => alreadySavedRequests.Keys.Contains(x.RequestId)); var requestEntitiesToUpdate = requestsToUpdate.ToEntities <RequestEntity, Request>(); await UpdateAlreadySavedRequestsAsync(requestEntitiesToUpdate, alreadySavedRequests); var requestsToAdd = model.requests.Where(x => !alreadySavedRequests.Keys.Contains(x.RequestId)); var requestEntitiesToAdd = requestsToAdd.ToEntities <RequestEntity, Request>(); await AddRequestsAsync(requestEntitiesToAdd); }