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 JoshiPosted Jun 5, 2023, 7:34 AM
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.
Thanks
Emmmanuel FIADUFEPosted Jun 5, 2023, 3:09 PM
Thank you Vishal, it's working
Emmmanuel FIADUFEPosted Jun 5, 2023, 3:04 PM
Naimish thank you very much for the explanation, I really appreciate it
Naimish MakwanaPosted Jun 5, 2023, 3:50 AM
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!