public ActionResult Delete(ReasonViewModel vm) { bool BeforeSave = true; try { BeforeSave = PurchaseIndentCancelDocEvents.beforeHeaderDeleteEvent(this, new PurchaseEventArgs(vm.id), ref db); } catch (Exception ex) { string message = _exception.HandleException(ex); TempData["CSEXC"] += message; EventException = true; } if (!BeforeSave) { TempData["CSEXC"] += "Failed validation before delete"; } if (ModelState.IsValid && BeforeSave && !EventException) { List <LogTypeViewModel> LogList = new List <LogTypeViewModel>(); //first find the Purchase Order Object based on the ID. (sience this object need to marked to be deleted IE. ObjectState.Deleted) var PurchaseIndentCancelHeader = db.PurchaseIndentCancelHeader.Find(vm.id); try { PurchaseIndentCancelDocEvents.onHeaderDeleteEvent(this, new PurchaseEventArgs(vm.id), ref db); } catch (Exception ex) { string message = _exception.HandleException(ex); TempData["CSEXC"] += message; EventException = true; } LogList.Add(new LogTypeViewModel { ExObj = Mapper.Map <PurchaseIndentCancelHeader>(PurchaseIndentCancelHeader), }); int doctypeid = PurchaseIndentCancelHeader.DocTypeId; //Then find all the Purchase Order Header Line associated with the above ProductType. var Line = (from p in db.PurchaseIndentCancelLine where p.PurchaseIndentCancelHeaderId == vm.id select p).ToList(); //Mark ObjectState.Delete to all the Purchase Order Lines. foreach (var item in Line) { LogList.Add(new LogTypeViewModel { ExObj = Mapper.Map <PurchaseIndentCancelLine>(item), }); item.ObjectState = Model.ObjectState.Deleted; db.PurchaseIndentCancelLine.Remove(item); //new PurchaseIndentCancelLineService(_unitOfWork).Delete(item.PurchaseIndentCancelLineId); } // Now delete the Purhcase Order Header //new PurchaseIndentCancelHeaderService(_unitOfWork).Delete(vm.id); PurchaseIndentCancelHeader.ObjectState = Model.ObjectState.Deleted; db.PurchaseIndentCancelHeader.Remove(PurchaseIndentCancelHeader); XElement Modifications = new ModificationsCheckService().CheckChanges(LogList); //Commit the DB try { if (EventException) { throw new Exception(); } db.SaveChanges(); //_unitOfWork.Save(); } catch (Exception ex) { string message = _exception.HandleException(ex); TempData["CSEXC"] += message; return(PartialView("_Reason", vm)); } try { PurchaseIndentCancelDocEvents.afterHeaderDeleteEvent(this, new PurchaseEventArgs(vm.id), ref db); } catch (Exception ex) { string message = _exception.HandleException(ex); TempData["CSEXC"] += message; } LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel { DocTypeId = PurchaseIndentCancelHeader.DocTypeId, DocId = PurchaseIndentCancelHeader.PurchaseIndentCancelHeaderId, ActivityType = (int)ActivityTypeContants.Deleted, UserRemark = vm.Reason, DocNo = PurchaseIndentCancelHeader.DocNo, xEModifications = Modifications, DocDate = PurchaseIndentCancelHeader.DocDate, DocStatus = PurchaseIndentCancelHeader.Status, })); return(Json(new { success = true })); } return(PartialView("_Reason", vm)); }