// Method to update CohortTechs private void UpdateCohortTechs(int[] selectedTechs, Cohort cohortToUpdate) { if (selectedTechs == null) { var unknown = (from t in _context.Tech where t.Name.Equals("(Unknown)") select t.Id).ToArray(); selectedTechs = unknown; } var selectedTechsHS = new HashSet <int>(selectedTechs); var cohortTechs = new HashSet <int> (cohortToUpdate.CohortTech.Select(c => c.Tech.Id)); foreach (var tech in _context.Tech) { if (selectedTechsHS.Contains(tech.Id)) { if (!cohortTechs.Contains(tech.Id)) { cohortToUpdate.CohortTech.Add(new CohortTech { CohortId = cohortToUpdate.Id, TechId = tech.Id }); } } else { if (cohortTechs.Contains(tech.Id)) { CohortTech techToRemove = cohortToUpdate.CohortTech.SingleOrDefault(c => c.TechId == tech.Id); _context.Remove(techToRemove); } } } }
public async Task <IActionResult> Add(string Id, DateTime StartDate, DateTime DemoDate, int[] selectedTechs, int[] selectedStaffs) { Cohort cohort = new Cohort(); cohort.Id = Id; cohort.StartDate = StartDate; cohort.DemoDate = DemoDate; if (selectedTechs != null) { cohort.CohortTech = new List <CohortTech>(); foreach (var tech in selectedTechs) { var techToAdd = new CohortTech { CohortId = cohort.Id, TechId = tech }; cohort.CohortTech.Add(techToAdd); } } else { cohort.CohortTech = new List <CohortTech>(); } if (selectedStaffs != null) { cohort.CohortStaff = new List <CohortStaff>(); foreach (var staff in selectedStaffs) { var staffToAdd = new CohortStaff { CohortId = cohort.Id, StaffId = staff }; cohort.CohortStaff.Add(staffToAdd); } } else { cohort.CohortStaff = new List <CohortStaff>(); } if (ModelState.IsValid) { _context.Add(cohort); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["Techs"] = PopulateAssignedTechData(cohort); ViewData["Staffs"] = PopulateAssignedTechData(cohort); return(View(cohort)); }