private void SaveSelectedServices(facility_contract facility_contract, bool updateExisting) { if (!string.IsNullOrEmpty(facility_contract.fct_selected_services)) { if (updateExisting) { #region handling Edit Scenario var list = facility_contract.fct_selected_services.Split(',').Select(m => m.ToInt()); var existingList = _facilityContractService.GetFacilityContractServices(facility_contract.fct_key).ToList(); var existingListKeys = existingList.Select(m => m.fcs_srv_key); var entitiesToRemove = existingList.Where(m => !list.Contains(m.fcs_srv_key)).ToList(); var entitiesToAdd = list.Where(m => !existingListKeys.Contains(m)).ToList(); _facilityContractService.RemoveServices(entitiesToRemove); entitiesToAdd.ForEach(m => { facility_contract.facility_contract_service.Add(new facility_contract_service { fcs_srv_key = m, fcs_fct_key = facility_contract.fct_key, fcs_created_by = loggedInUser.Id, fcs_created_by_name = loggedInUser.FullName, fcs_is_active = true, fcs_created_date = DateTime.Now.ToEST() }); }); #endregion } else { #region Add New Facility Contract with Selected Services facility_contract.fct_selected_services.Split(',').Select(m => m.ToInt()).ToList().ForEach(m => { facility_contract.facility_contract_service.Add(new facility_contract_service { fcs_srv_key = m, fcs_fct_key = facility_contract.fct_key, fcs_created_by = loggedInUser.Id, fcs_created_by_name = loggedInUser.FullName, fcs_is_active = true, fcs_created_date = DateTime.Now.ToEST() }); }); #endregion } _facilityContractService.SaveChanges(); } }