Home > Back-end >  Error: An error occurred while saving the entity changes in .NET
Error: An error occurred while saving the entity changes in .NET

Time:01-07

I'm getting this error when I'm posting data to my API:

An error occurred while saving the entity changes. See the inner exception for details.
 
---> Microsoft.Data.SqlClient.SqlException (0x80131904): 

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_OrderLine_Order_OrderID". 

The conflict occurred in database "AnimimoMicroservicesNewOrderServiceContext-feca99ec-8feb-4680-b1f5-f1a32825a8c1", table "dbo.Order", column 'OrderID'.

This is the HttpPost method where I'm posting my model to the database:

// POST: api/Orders
        [HttpPost]
        public async Task<ActionResult<Order>> PostOrder(PostOrderDTO postOrderDto)
        {

            var order = new Order(postOrderDto.Identifier, postOrderDto.Customer);

            var json = JsonConvert.SerializeObject(order);

            var content = new StringContent(json, Encoding.UTF8, "application/json");

            _context.Order.Add(order);

            var basket = await GetBasketItems(postOrderDto.Identifier);
            var newOrderId = order.OrderID;

            foreach (var item in basket.Items)
            {
                var orderLine = new OrderLine
                {
                    OrderID = newOrderId,
                    ProductId = item.ProductId,
                    Quantity = item.Quantity
                };

                _context.OrderLine.Add(orderLine);
            };

            await _context.SaveChangesAsync();

            return CreatedAtAction("GetOrder", new { id = order.OrderID }, order);
        }

The 'OrderID' is auto-generated when posting to Order but I need same generated OrderID to be posted and saved in OrderLine as well, here is what my Order database looks like: OrderDB So the OrderID that is generated when I post and save to Order is what I'm trying to get to my OrderLine DB which looks like this in my database: OrderLineDB

It only says NULL, then I tried the following code above in the POST method to post the OrderID but got the error as stated above, I'm trying to resolve this

This is my Order.cs model:

public class Order
    {
        public Order(int orderID, string identifier, string customer)
        {
            OrderID = orderID;
            Identifier = identifier;
            Customer = customer;
        }

        public Order(string identifier, string customer)
        {
            Identifier = identifier;
            Customer = customer;
        }

        [Key]
        public int OrderID { get; set; }
        public string Identifier { get; set; }

        public string Customer { get; set; }

        //[NotMapped]
        public IEnumerable<OrderLine> Items { get; set; } = new List<OrderLine>();
    }

The 'OrderID' in Order.cs model is a foreign key to the OrderLine table which looks like this:

public class OrderLine
    {
        public int Id { get; set; }
        public int OrderID { get; set; }
        public int ProductId { get; set; }
        public int Quantity { get; set; }
    }

How do I fix this? I want the generated OrderID of my Order table to be posted to my OrderLine table with the same Post method but I only got the error as stated above, can I fix this? Thanks for any help in advance

CodePudding user response:

When adding the order you did not save your changes. This means that the order object does not have an id yet. If you save after _context.Order.Add(order); and before adding the id to the orderline this wil be resolved.

CodePudding user response:

you have to fix the navigaion properties

public class OrderLine
    {
        public int Id { get; set; }
       public int Quantity { get; set; }

        public int OrderID { get; set; }
        public int ProductId { get; set; }

         public  virtual Order Order { get; set; }
        public virtual Product { get; set; }
       
    }

and in the code remove _context.Order.Add(order);

            var basket = await GetBasketItems(postOrderDto.Identifier);
  
            foreach (var item in basket.Items)
            {
                var orderLine = new OrderLine
                {
                    Order = order,
                    ProductId = item.ProductId,
                    Quantity = item.Quantity
                };

                _context.OrderLine.Add(orderLine);
            };

            await _context.SaveChangesAsync();

and just because of curiosity, what is this for ?

var json = JsonConvert.SerializeObject(order);
 var content = new StringContent(json, Encoding.UTF8, "application/json");
  •  Tags:  
  • Related