Hello Team,
Please am trying to delete data from two table but is not working, kindly assist.
public ActionResult DeleteStaff(int StaffId, int CompanyId)
{
try
{
ASPNETMASTERPOSTEntities db = new ASPNETMASTERPOSTEntities();
var company = db.tblCompany.Where(x => x.CompanyId == CompanyId ).FirstOrDefault();
var Staff = db.tblStaffs.Where(x => x.StaffId == StaffId ).FirstOrDefault();
db.tblCompany.Remove(company);
db.tblStaffs.Remove(Staff);
db.SaveChanges();
return Json(true, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}

Vishal JoshiRank #377 · 6.7K reputationPosted Jun 5, 2023, 3:34 AM EDT
Hello,
Please check the Front-end code from where you are calling API. make sure CompanyId and StaffId passing properly.
Also, add a check if the company and staff are not null and empty before calling the remove method. check below sample code.
public ActionResult DeleteStaff(int StaffId, int CompanyId) { try { ASPNETMASTERPOSTEntities db = new ASPNETMASTERPOSTEntities(); var company = db.tblCompany.Where(x => x.CompanyId == CompanyId ).FirstOrDefault(); var Staff = db.tblStaffs.Where(x => x.StaffId == StaffId ).FirstOrDefault(); if(company != null) db.tblCompany.Remove(company); if(Staff != null) db.tblStaffs.Remove(Staff); db.SaveChanges(); return Json(true, JsonRequestBehavior.AllowGet); } catch (Exception) { return Json(false, JsonRequestBehavior.AllowGet); } }Thanks
Naimish MakwanaRank #324 · 7.7K reputationPosted Jun 4, 2023, 11:50 PM EDT
There could be a few reasons why the data is not getting deleted. Here are a few things you can check:
Make sure that the
CompanyIdandStaffIdvalues you're passing to the method are correct and correspond to existing records in the database. If the IDs are not valid, theFirstOrDefaultmethod will return null, and the removal won't happen.Check if there are any foreign key constraints defined between the two tables (
tblCompanyandtblStaffs). If there are constraints, you need to delete the child records (tblStaffs) before deleting the parent record (tblCompany).Thanks!
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jun 5, 2023, 11:04 AM EDT
Naimish thank you very much for the explanation, I really appreciate it
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jun 5, 2023, 11:09 AM EDT
Thank you Vishal, it's working