Hello Team, this is my Home controller query, it always duplicate data when I try to update saved data, kindly help.
public JsonResult UpdateInvoiceSale(tblSale sale, List salesDetail, List deleted) {
MasterMVCPOS.Helper.AppHelper.ReturnMessage retMessage = new AppHelper.ReturnMessage();
ASPNETMASTERPOSTEntities db = new ASPNETMASTERPOSTEntities();
retMessage.IsSuccess = true;
if (deleted != null) {
foreach(var item in deleted) {
var data = db.tblSalesDetails.Where(x => x.SalesDetailId == item).FirstOrDefault();
db.tblSalesDetails.Remove(data);
}
}
foreach(var item in salesDetail) {
if (item.SalesDetailId > 0) {
db.Entry(item).State = EntityState.Modified;
retMessage.Message = "Update successfully!";
} else {
sale.tblSalesDetails.Add(new tblSalesDetail {
ProductId = item.ProductId, UnitPrice = item.UnitPrice, Quantity = item.Quantity, LineTotal = item.LineTotal
});
var prd = db.tblProductStocks.Where(x => x.ProductId == item.ProductId && x.Quantity > 0).FirstOrDefault();
prd.Quantity = prd.Quantity - item.Quantity;
db.Entry(prd).State = EntityState.Modified;
db.tblSales.Add(sale);
retMessage.Message = "Save successfully!";
}
}
try {
db.SaveChanges();
} catch (Exception) {
retMessage.IsSuccess = false;
}
return Json(retMessage, JsonRequestBehavior.AllowGet);
}
Amit MohantyPosted Jun 30, 2023, 10:13 AM
The problem lies in foreach loop. Try this:
Deepak RawatPosted Jun 30, 2023, 10:07 AM
issue with your code is that you are adding the
saleobject to thedb.tblSalestable inside theforeachloop. This is causing the data to be duplicated every time the loop iterates. To fix this issue, you should move thedb.tblSales.Add(sale)line outside the loop.n this modified code, the
db.tblSales.Add(sale)line is moved outside the loop to ensure that thesaleobject is added to the database only once. This should prevent the duplication of data when updating saved records.I made a few other improvements to your code, such as checking for null values before removing or modifying data and using the
FirstOrDefault()method instead ofFirstOrDefault()in the appropriate places.