public ActionResult SaveItem(ItemViewModel itemModel)
{
bool result = false;
try
{
// Step 1: Save Category
tblCategory objCategory = objRestaurantDBEntities.tblCategories
.SingleOrDefault(x => x.CategoryId == itemModel.CategoryId) ?? new tblCategory();
if (itemModel.CategoryId <= 0)
{
objCategory.CategoryName = itemModel.CategoryName;
objRestaurantDBEntities.tblCategories.Add(objCategory);
objRestaurantDBEntities.SaveChanges(); // Save to generate CategoryId
}
// Ensure objCategory has an ID
if (objCategory.CategoryId <= 0)
{
return Json(new { success = false, message = "Failed to save category." });
}
// Step 2: Save Item
tblItem objItem = objRestaurantDBEntities.tblItems
.SingleOrDefault(x => x.ItemId == itemModel.ItemId) ?? new tblItem();
objItem.PCode = itemModel.PCode;
objItem.ItemName = itemModel.ItemName;
objItem.CostPrice = itemModel.CostPrice;
objItem.ItemPrice = itemModel.ItemPrice;
objItem.Vat = itemModel.Vat;
objItem.ExpiringDate = itemModel.ExpiringDate;
objItem.Active = itemModel.Active;
objItem.CategoryId = objCategory.CategoryId; // Assign correct category ID
if (itemModel.ItemId <= 0) // New Item
{
objRestaurantDBEntities.tblItems.Add(objItem);
}
objRestaurantDBEntities.SaveChanges(); // Save Item
if (objItem.ItemId <= 0)
{
return Json(new { success = false, message = "Failed to save item. ItemId not generated." });
}
// Step 3: Save Quantity (Ensure itemModel.tblQuantities is not null)
if (itemModel.tblQuantities != null)
{
tblQuantity objQnty = objRestaurantDBEntities.tblQuantities
.SingleOrDefault(x => x.QuantityId == itemModel.tblQuantities.QuantityId) ?? new tblQuantity();
objQnty.InitialQty = itemModel.tblQuantities.InitialQty;
objQnty.Quantity = itemModel.tblQuantities.Quantity;
objQnty.ItemId = objItem.ItemId;
if (itemModel.tblQuantities.QuantityId <= 0) // New Quantity Entry
{
objRestaurantDBEntities.tblQuantities.Add(objQnty);
}
objRestaurantDBEntities.SaveChanges(); // Save Quantity Data
}
result = true;
}
catch (Exception ex)
{
// Log the error properly (Assuming you have a logging mechanism)
Console.WriteLine(ex.ToString());
return Json(new { success = false, message = "An error occurred: {ex.Message}" });
}
return Json(new { success = result, message = "Item saved successfully." });
}
Jignesh KumarPosted Mar 7, 2025, 4:52 PM
Hello Emmanual.
Please check below code where you need to check, I think your are passing wrong parameter
itemModel.tblQuantities.QuantityId ----> itemModel..QuantityId and make sure to pass correct values from jquery page
Emmmanuel FIADUFEPosted Mar 4, 2025, 12:37 PM
Hello team.
As I tried to save data, you can see it below
Jignesh KumarPosted Mar 4, 2025, 4:03 AM
Hello Emmanuel,
Have you checked in step-3 and line,
Are you getting objITem.ItemId we are getting correct ItemId after saveChanges on item table. If not then we need to check here why itemId not comming here.
Please check here and you will find root cause for this.
Jignesh KumarPosted Mar 3, 2025, 12:11 PM
Hello Emmanuel,
Please check on below code, you need to do below changes, When you are using EF then please use transaction, it will help to maintain data integrity.
Emmmanuel FIADUFEPosted Mar 3, 2025, 11:04 AM
Hello Mr Pual ,
thank you for your resposnse but I'm getting error from where we are calling the SaveOrUpdate quantity.
Error 2 The best overloaded method match for 'SmartRestaurantManagement.Controllers.HomeController.SaveOrUpdateQuantity(SmartRestaurantManagement.ViewModel.QuantityViewModel, int)' has some invalid arguments
Tuhin PaulPosted Mar 2, 2025, 7:46 PM
A refactored version of the method:
Tuhin PaulPosted Mar 2, 2025, 7:45 PM
Error Handling
Issue : The error message in the
catchblock uses string interpolation incorrectly ("An error occurred: {ex.Message}"). This will not replace{ex.Message}with the actual exception message.Fix : Use proper string interpolation:
Improvement : Instead of logging errors to the console, use a proper logging framework like Serilog , NLog , or Microsoft.Extensions.Logging .
Null Checks
itemModel.tblQuantitiesis null-checked but does not validate other properties ofitemModel(e.g.,CategoryName,PCode, etc.).Database Context Management
objRestaurantDBEntities.SaveChanges()multiple times without wrapping it in a transaction. If one step fails after earlier steps succeed, the database could end up in an inconsistent state.Performance Optimization
SingleOrDefaultmultiple times to check for existing records. This can result in unnecessary database queries.JSON Response
CategoryIdorItemId).Code Readability
Tuhin PaulPosted Mar 2, 2025, 7:42 PM
Key Steps
Category Handling :
CategoryIdis less than or equal to 0, it assumes the category is new and creates it.CategoryIdis valid before proceeding.Item Handling :
ItemIdis less than or equal to 0 to determine if the item is new.CategoryId(from the previously saved category) to the item.Quantity Handling :
tblQuantitiesis provided in theitemModel, it saves or updates the quantity record.ItemId.Error Handling :
try-catchblock is used to handle exceptions.Console.WriteLine) and returned as part of the JSON response.JSON Response :
success(boolean) andmessage(string) properties.Tuhin PaulPosted Mar 2, 2025, 7:42 PM
The provided code is a method in an ASP.NET MVC controller that handles saving an item, its associated category, and quantity information to a database.
The
SaveItemmethod performs the following tasks:tblCategory) if it doesn't already exist.tblItem) and associates it with the saved category.tblQuantity) for the item.It returns a JSON response indicating success or failure, along with an appropriate message.
Emmmanuel FIADUFEPosted Mar 2, 2025, 7:14 PM
Any help will be highly appreciated
Emmmanuel FIADUFEPosted Mar 1, 2025, 5:20 PM
Data got save in the item table alright but the quantity table remain empty,
Kindly help.
Emmmanuel FIADUFEPosted Mar 1, 2025, 5:04 PM
It's still not working
Eliana BlakePosted Mar 1, 2025, 12:40 PM
It seems that the issue you are facing is related to saving the Quantity data into tblQuantities. The problem lies in how the QuantityId is handled within the code snippet you provided. Let's break it down and identify the potential issue:
1. The code snippet attempts to save the Quantity data by checking if itemModel.tblQuantities is not null.
2. It then tries to retrieve a tblQuantity object based on itemModel.tblQuantities.QuantityId.
3. If the retrieved tblQuantity object is null (i.e., not found in the database), a new tblQuantity object is created.
The potential problem arises when trying to save the Quantity data because the QuantityId is used as a unique identifier. However, the QuantityId is not being properly handled when creating a new Quantity entry.
In the code snippet:
The QuantityId comparison `x.QuantityId == itemModel.tblQuantities.QuantityId` assumes that the QuantityId from the itemModel is already assigned or retrieved from the database. If QuantityId is not set or generated correctly in itemModel.tblQuantities, it will not match any existing QuantityId in tblQuantities, causing a new entry to be created every time, even when it should be associating the Quantity with an existing Item.
To address this issue, ensure that the QuantityId is correctly generated or retrieved for the specific Quantity related to the Item. If QuantityId is supposed to be auto-generated by the database, make sure that the correct mechanisms are in place to handle this auto-generation and association with the Item.
Additionally, if QuantityId needs to be assigned or retrieved before saving the Quantity, consider updating the logic to handle QuantityId generation or retrieval before creating a new tblQuantity object.
By addressing how QuantityId is managed and associated with the Item, you should be able to resolve the issue of ItemId not saving into tblQuantities effectively. Let me know if you need further clarification or assistance with this matter!