i'm biulding a web application and when the users log in and trying to buy somthing from web for another time this error apears
SqlException: Cannot insert explicit value for identity column in table 'orderFactors' when IDENTITY_INSERT is set to OFF.
public IActionResult AddToCart(int itemId)
{
var product = _context.Products.Include(p => p.Item).SingleOrDefault(p => p.ItemId == itemId);
if (product != null)
{
int userId = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier).ToString());
var order = _context.orderFactors.FirstOrDefault(o => o.UserId == userId && !o.IsFinally);
if (order != null)
{
var orderDetail = _context.orderDetails.FirstOrDefault(o => o.OrderId == order.OrderId && o.ProductId == product.Id);
if (orderDetail != null)
{
orderDetail.Count += 1;
}
else
{
_context.orderFactors.Add(order);
_context.orderDetails.Add(new OrderDetail()
{
OrderId = order.OrderId,
ProductId = product.Id,
price = product.Item.Price,
Count = 1
});
}
}
else
{
order = new OrderFactor()
{
IsFinally = false,
CreateDate= DateTime.Now,
UserId= userId
};
_context.orderFactors.Add(order);
_context.SaveChanges();
_context.orderDetails.Add(new OrderDetail()
{
OrderId = order.OrderId,
ProductId = product.Id,
price = product.Item.Price,
Count = 1
});
}
_context.SaveChanges();
}
return RedirectToAction("ShowCart");
}
You are reading from the DB here
But then you try to add the value again here if orderDetail is not null
The order object that you have read will have an Id and therefore the DB thinks you are trying to add the same Id to that table.