I have a scenario where I need to handle multiple tasks, each potentially associated with an item. The setup involves two services: ItemService and TaskService. The API Gateway is responsible for calling ItemService to create an item, get its ID, and then assign it to a task before creating the task.
Here’s a simplified version of the code I’m working with:
foreach (var task in request.Tasks)
{
if (HasItem(task))
{
var itemIdOrError = await CreateItemOrErrorAsync(request, cancellationToken, stopInformation, task);
if (itemIdOrError.IsError) return itemIdOrError.Errors;
task.Item.Id = itemIdOrError.Value;
}
var taskDto = task.Adapt<Services.TaskManagement.Web.Shared.Stop.Commands.TaskDto>();
taskDto.BusinessUnitId = stopInformation.BusinessUnitId;
taskDto.ClientId = stopInformation.ClientId;
var taskIdOrError = await _taskManagementClient
.AddTasksAsync(request.DomainId, request.StopId, taskDto, cancellationToken)
.ConfigureAwait(false);
if (taskIdOrError.IsError) return Error.Validation(description: "Error when adding TaskId");
}
The requirement is to ensure that all operations are transactional. Specifically:
- If creating an item fails, the operation should roll back.
- If creating a task fails, all previously created items and tasks in the current batch should roll back.
In both services, I’m using Dapper to interact with the database (SQL Server).
I would like to know if there is a simpler way to do it since I’m using SQL Server.