Hello Team,
The error message I'm getting says that UserId does not exist, and I tried to create a relationship between user table and tblOrder table but it also says foreign key conflict whenever I tried to insert data so i remove the relationship, the Schema for both tblUser and tblOrder is Order, and though the UserId is present in the tblUser, kindly assist.
public int AddOrder(OrderViewModel objOrderViewModel)
{
// Check if User Exists
var userExists = objRestaurantDBEntities.tblUsers
.Any(u => u.UserId == objOrderViewModel.UserId);
if (!userExists)
{
throw new Exception("? Error: UserId (" + objOrderViewModel.UserId + ") does not exist in tblUser.");
}
// Create Order Object
tblOrder objOrder = new tblOrder
{
CustomerId = objOrderViewModel.CustomerId,
FinalTotal = objOrderViewModel.FinalTotal,
OrderDate = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"),
OrderNumber = DateTime.Now.ToString("ddMMMyyyyHHmmss"),
PaymentTypeId = objOrderViewModel.PaymentTypeId,
UserId = objOrderViewModel.UserId
};
objRestaurantDBEntities.tblOrders.Add(objOrder);
objRestaurantDBEntities.SaveChanges();
int OrderId = objOrder.OderId; // ? Ensure correct field name
// List to store Order Details
List
foreach (var item in objOrderViewModel.ListofOrderDetailViewModel)
{
tblOrderDetail objOrderDetails = new tblOrderDetail
{
OderId = OrderId,
Discount = item.Discount,
ItemId = item.ItemId,
Total = item.Total,
UnitPrice = item.UnitPrice,
Quantity = Convert.ToInt32(item.Quantity),
Vat = item.Vat
};
orderDetailsList.Add(objOrderDetails);
// Check if Item exists in stock before updating
var tblQty = objRestaurantDBEntities.tblQuantities
.SingleOrDefault(x => x.ItemId == item.ItemId);
if (tblQty != null)
{
int newQuantity = Convert.ToInt32(tblQty.Quantity) - Convert.ToInt32(item.Quantity);
tblQty.Quantity = newQuantity >= 0 ? newQuantity : 0; // Prevent negative stock
objRestaurantDBEntities.Entry(tblQty).State = EntityState.Modified;
}
}
// Save all Order Details in one go
objRestaurantDBEntities.tblOrderDetails.AddRange(orderDetailsList);
objRestaurantDBEntities.SaveChanges(); // ? Single SaveChanges() for better performance
return OrderId;
}
}
}
Emmmanuel FIADUFEPosted Apr 13, 2025, 12:48 PM
Hello team,
Any additional help on this question will be highly appreciated
Emmmanuel FIADUFEPosted Apr 10, 2025, 10:59 PM
But when I remove the user code from the class, I'm able to save the data into the database without any error.
Can anyone assist me with the user code, so that when I save order it will also save the userId at the same time.
Emmmanuel FIADUFEPosted Apr 9, 2025, 11:26 PM
This is my current update now in the controller, though it doesn't return the error again that the User is not found but the Order data do not save in the database.
public JsonResult SaveSales(OrderViewModel objOrderViewModel)
{
// Get logged-in user's ID from session
int? userId = Session["UserId"] as int?;
if (userId == null)
{
return Json(new { success = false, message = "User is not logged in." }, JsonRequestBehavior.AllowGet);
}
//Assign it to the ViewModel
objOrderViewModel.UserId = userId.Value;
// Proceed with saving the order
OrderRepositories objOrderRepositories = new OrderRepositories();
var OrderNumber = objOrderRepositories.AddOrder(objOrderViewModel);
return Json(new { success = true, orderNumber = OrderNumber }, JsonRequestBehavior.AllowGet);
}
Emmmanuel FIADUFEPosted Apr 9, 2025, 8:51 PM
Hello Team,
Please let me bring in some clarity here, may be that will help us find the solution
my earlier code is in a class and this is my controller code, and my login query is in the controller
public JsonResult SaveSales(OrderViewModel objOrderViewModel)
{
OrderRepositories objOrderRepositories = new OrderRepositories();
var OrderNumber = objOrderRepositories.AddOrder(objOrderViewModel);
return Json(OrderNumber, JsonRequestBehavior.AllowGet);
}
Emmmanuel FIADUFEPosted Apr 8, 2025, 5:36 PM
Hello team,
Please any further help will be highly appreciated.
Thanks
Emmmanuel FIADUFEPosted Apr 8, 2025, 9:21 AM
Hello Paul,
this is the error that popup after effecting the changes, User with ID {objOrderViewModel.UserId} not found.
Thank you for your response, as I run sql query this is the result as you can see.
Tuhin PaulPosted Apr 8, 2025, 1:42 AM
Before inserting an order, your code checks if the
UserIdexists. However, ensure that theUserIdyou're passing is the exact one stored in the database (case-sensitive or not, depending on your database's collation settings).You can modify your check as follows to explicitly throw an exception if the user is not found:
This will provide a clearer error message when the user does not exist in the
tblUsertable.Tuhin PaulPosted Apr 8, 2025, 1:41 AM
This is related to the
UserIdbeing referenced in yourtblOrdertable, and the system not being able to find a corresponding user in thetblUsertable.Even though you've removed the relationship, there may still be foreign key constraints in the database itself. Run the following query to check for any remaining foreign key constraints:
If any foreign key constraints are found, you might need to drop or adjust them in the database.
Emmmanuel FIADUFEPosted Apr 7, 2025, 2:25 PM
Hello Amira,
Thanks for your response, after removing the relationship there was no foreign key conflict again, but says UserId does not exist meanwhile it is the same username I used to login before trying to save the data into the database
Amira BedhiafiPosted Apr 7, 2025, 10:50 AM
It is either the UserId doesn't exist (we can talk about foreign key constraint violation) or the relationship between tables is causing conflicts.
Even though you removed the relationship, the database might still have constraints:
Or simply add explicit validation: