I am trying to create POST, PATCH, and PUT methods in a .NET Core Web API for a database table that contains a foreign key. I am unsure if the problem lies in my method or in the way I am testing my method on swagger. My methods for tables on the same DB that do not contain foreign keys work perfectly.
My DB table is hosted on SQL Server and has CustomerId as a foreign key. When I test my POST method on Swagger, I receive a 400 error that states that "The Customer field is required".
My POST method in Visual Studio is as follows:
[HttpPost]
public async Task<ActionResult<Order>> PostOrder(Order order)
{
if (_context.Orders == null)
{
return Problem("Entity set 'ecopowerdatabaseContext.Orders' is null.");
}
_context.Orders.Add(order);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (OrderExists(order.OrderId))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtAction("GetOrder", new { id = order.OrderId }, order);
}
I have modified by Request Body to include all the information of the referenced Customer field, but when I do that I get a conflict error because it tries to post to the customer table with the Id that already exists.
2
Answers
I found a solution. The problem seems to be solved if I add the required fields for an order into the input parameters of my method so that they are explicitly entered in their own separate textboxes in Swagger. Instead of having an order object as the input parameter - because the object does not exist yet. Then, I create a new Order object inside the method and assign all required attributes before passing the new order object to my Add() method. The correct code is as follows:
You have to retrieve the Customer entity first before populating your ORDER.
So, you can edit your method like this: