public async Task <global::Elsa.Models.WorkflowInstance> SaveAsync(global::Elsa.Models.WorkflowInstance instance, CancellationToken cancellationToken = default) { var existingEntity = await _workflowInstanceRepository .GetByInstanceIdAsync(instance.Id, true, cancellationToken); if (existingEntity == null) { var workflowInstance = new WorkflowInstance(_guidGenerator.Create().ToString()); _objectMapper.Map(instance, workflowInstance); workflowInstance.Activities = instance.Activities .Select(t => new ActivityInstance(_guidGenerator.Create().ToString()) { Type = t.Value.Type, ActivityId = t.Key, State = t.Value.State, Output = t.Value.Output, } ).ToList(); workflowInstance.BlockingActivities = instance.BlockingActivities.Select(t => new BlockingActivity(_guidGenerator.Create().ToString()) { ActivityId = t.ActivityId, ActivityType = t.ActivityType }).ToList(); await _workflowInstanceRepository.InsertAsync(workflowInstance, cancellationToken : cancellationToken); await _unitOfWorkManager.Current.SaveChangesAsync(cancellationToken); return(Map(workflowInstance)); } else { _activityInstanceRepository.BatchDeleteActivityInstances(existingEntity.Activities.ToList()); _workflowInstanceRepository.BatchDeleteBlockingActivitys(existingEntity.BlockingActivities.ToList()); existingEntity.Activities.Clear(); existingEntity.BlockingActivities.Clear(); var entity = _objectMapper.Map(instance, existingEntity); await _workflowInstanceRepository.UpdateAsync(entity, cancellationToken : cancellationToken); await _unitOfWorkManager.Current.SaveChangesAsync(cancellationToken); return(Map(entity)); } }