public void UpdateStudentEvents(BPA_TrackerContext context, string[] selectedEvents, Student StudentToUpdate) { if (selectedEvents == null) { StudentToUpdate.AssignEvents = new List <AssignEvent>(); return; } var selectedEventsHS = new HashSet <string>(selectedEvents); var StudentEvents = new HashSet <int> (StudentToUpdate.AssignEvents.Select(c => c.Event.EventID)); foreach (var Event in context.Event) { if (selectedEventsHS.Contains(Event.EventID.ToString())) { if (!StudentEvents.Contains(Event.EventID)) { StudentToUpdate.AssignEvents.Add( new AssignEvent { StudentID = StudentToUpdate.StudentID, EventID = Event.EventID }); } } else { if (StudentEvents.Contains(Event.EventID)) { AssignEvent EventToRemove = StudentToUpdate .AssignEvents .SingleOrDefault(i => i.EventID == Event.EventID); context.Remove(EventToRemove); } } } }
public async Task <IActionResult> OnPostAsync(string[] selectedCourses) { if (!ModelState.IsValid) { return(Page()); } var newStudent = new Student(); if (selectedCourses != null) { newStudent.AssignEvents = new List <AssignEvent>(); foreach (var course in selectedCourses) { var coursetoadd = new AssignEvent { EventID = int.Parse(course) }; newStudent.AssignEvents.Add(coursetoadd); } } if (await TryUpdateModelAsync <Student>( newStudent, "Student", i => i.FirstName, i => i.LastName, i => i.StudentPhone, i => i.StudentEmail, i => i.ParentName, i => i.ParentPhone, i => i.ParentEmail)) { _context.Student.Add(newStudent); await _context.SaveChangesAsync(); return(RedirectToPage("./Index")); } PopulateAssignedEventData(_context, newStudent); return(Page()); }