skip to Main Content

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 Request Body on Swagger

The error message I receive

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


  1. Chosen as BEST ANSWER

    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:

    [HttpPost]
    public async Task<ActionResult<Order>> PostOrder(short OrderId, 
    DateTime OrderDate, short CustomerId, string Address)
    {
        if (_context.Orders == null)
        {
            return Problem("Entity set 'ecopowerdatabaseContext.Orders'  
            is null.");
        }
    
        Order order = new Order();
        order.OrderId = OrderId;
        order.OrderDate = OrderDate;
        order.CustomerId = CustomerId;
        order.DeliveryAddress = Address;
    
        _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);
    }
    

  2. You have to retrieve the Customer entity first before populating your ORDER.

    var customer = await _context.Customers.FirstOrDefaultAsync(c => c.CustomerId == order.CustomerId);
    
        if(customer == null) {
            return BadRequest();
        }
    
        order.Customer = customer;
    

    So, you can edit your method like this:

    [HttpPost]
    public async Task<ActionResult<Order>> PostOrder(Order order)
    {
        if (_context.Orders == null)
        {
            return Problem("Entity set 'ecopowerdatabaseContext.Orders'  is null.");
        }
        
        var customer = await _context.Customers.FirstOrDefaultAsync(c => c.CustomerId == order.CustomerId);
    
        if(customer == null) {
            return BadRequest();
        }
    
        order.Customer = customer;
        
        _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);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search