So I have this small car shop project for university and when I want to place order I get this:
Microsoft.EntityFrameworkCore.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'
PostgresException: 23503: insert or update on table "OrderDetail" violates foreign key constraint "FK_OrderDetail_Order_orderId"
I use .NET Core 3.0.1 and PostgreSQL 4.1.2. The database is deployed on heroku.
The piece of code that causes the trouble:
namespace Shop.Data.Repository
{
public class OrdersRepository : IAllOrders
{
private readonly AppDBContent appDBContent;
private readonly ShopCart shopCart;
public OrdersRepository(AppDBContent appDBContent, ShopCart shopCart)
{
this.appDBContent = appDBContent;
this.shopCart = shopCart;
}
public void createOrder(Order order)
{
order.orderTime = DateTime.Now;
appDBContent.Order.Add(order);
var items = shopCart.listShopItems;
var orderDetail = new OrderDetail();
orderDetail.orderId = order.id;
foreach (var car in items)
{
orderDetail.carId = car.car.id;
orderDetail.price = car.car.price;
}
appDBContent.OrderDetail.Add(orderDetail);
appDBContent.SaveChanges();
}
}
}
OrderDetail Model:
namespace Shop.Data.Models
{
public class OrderDetail
{
public int id { get; set; }
public int orderId { get; set; }
public int carId { get; set; }
public int price { get; set; }
public virtual Car car { get; set; }
public virtual Order order { get; set; }
}
}
Order Model:
namespace Shop.Data.Models
{
public class Order
{
[BindNever]
public int id { get; set; }
public string name { get; set; }
public string surname { get; set; }
public string address { get; set; }
public string phone { get; set; }
public string email { get; set; }
public DateTime orderTime { get; set; }
public List<OrderDetail> orderDetails { get; set; }
}
}
OrderController:
namespace Shop.Controllers
{
public class OrderController : Controller
{
private readonly IAllOrders allOrders;
private readonly ShopCart shopCart;
public OrderController(IAllOrders allOrders, ShopCart shopCart)
{
this.allOrders = allOrders;
this.shopCart = shopCart;
}
public IActionResult Checkout()
{
return View();
}
[HttpPost]
public IActionResult Checkout(Order order)
{
shopCart.listShopItems = shopCart.getShopItems();
if (shopCart.listShopItems.Count == 0)
ModelState.AddModelError("", "You have no items in your cart!");
if (ModelState.IsValid)
{
allOrders.createOrder(order);
return RedirectToAction("Complete");
}
return View(order);
}
public IActionResult Complete()
{
ViewBag.Message = "Your order was processed successfully";
return View();
}
}
}
I've been trying to fix it for a couple of days but still can't figure out what's the problem, that'd be great if some of you guys could help me :)
