I have an endpoint that instatiates a class then add tasks to this and finally save in database:
[Route("api/[controller]")]
public class BusinessProposalController(IBusinessProposalRepository businessProposalRepository, IWorkTaskRepository workTaskRepository, IWorkTaskTypeRepository workTaskTypeRepository, IUnitOfWork unitOfWork): ControllerBase
{
[HttpPost]
public async Task<ActionResult> Create([FromBody] CreateBusinessProposalRequest request, CancellationToken cancellationToken)
{
// add request body validator
var businessProposal = request.ToEntity();
businessProposalRepository.Create(businessProposal);
var workTasks = request.WorkTasks.Select(w => w.ToEntity(businessProposal.Id)).ToList();
foreach (var workTask in workTasks)
{
var workTaskType = await workTaskTypeRepository.GetById(workTask.WorkTaskTypeId, cancellationToken);
if (workTaskType == null)
{
return BadRequest(new { message = $"Work task type {workTask.WorkTaskTypeId} not found"});
}
workTaskRepository.Create(workTask);
}
await unitOfWork.Commit(cancellationToken);
return Ok(new { id = businessProposal.Id});
}
}
a request with this body:
{
"name": "test",
"customer": "test",
"address": "test",
"workTasks": [
{
"unitCost": 20.0,
"quantity": 3,
"workTaskTypeId": "d4a1f4fc-148a-4a91-ae8b-6c364fc9a558"
}
]
}
produces this error when i remove the line that checks if worktaskType is already in db:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
---> Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 19: 'FOREIGN KEY constraint failed'.
at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
at Microsoft.Data.Sqlite.SqliteDataReader.NextResult()
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at ReportGenerator.Infra.Repositories.UnitOfWork.Commit(CancellationToken cancellationToken) in C:Userspedro.ferrariDesktopdevworkreport-generatorReportGeneratorReportGenerator.InfraRepositoriesUnitOfWork.cs:line 12
at ReportGenerator.API.Controllers.BusinessProposalController.Create(CreateBusinessProposalRequest request, CancellationToken cancellationToken) in C:Userspedro.ferrariDesktopdevworkreport-generatorReportGeneratorReportGenerator.APIControllersBusinessProposalController.cs:line 37
at lambda_method5(Closure, Object)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
HEADERS
=======
Accept: */*
Connection: keep-alive
Host: localhost:5294
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36
Accept-Encoding: gzip, deflate, br, zstd
Accept-Language: pt-BR,pt
Content-Type: application/json
Origin: http://localhost:5294
Referer: http://localhost:5294/swagger/index.html
Content-Length: 205
sec-ch-ua: "Not)A;Brand";v="99", "Brave";v="127", "Chromium";v="127"
sec-ch-ua-platform: "Windows"
sec-ch-ua-mobile: ?0
Sec-GPC: 1
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
The thing is that i preload the database with all WorkTaskTypes that come from another source. I can access this values with my another endpoint that get all worktasktypes, like here:
and i have a lot of registers:
Debugging the code i found out that i can’t find the WorkTaskType by providing the Id while creating my entity in the ToEntity method:
public static class WorkTaskMapper
{
public static WorkTask ToEntity(this CreateWorkTaskRequest request, Guid BusinessProposalId)
{
return new WorkTask
{
BusinessProposalId = BusinessProposalId,
UnitCost = request.UnitCost,
Quantity = request.Quantity,
WorkTaskTypeId = request.WorkTaskTypeId
};
}
}
This don’t point to any WorkTaskType and raise this FK Constraint error.
Can someone help me? I’m kinda lost right now