/// <summary> /// Edits the <see cref="Department"/> using <see cref="EditDepartmentServiceModel"/>. /// </summary> /// <param name="model">Number of modified entities.</param> /// <returns>Service model with <c>Id</c>, <c>Name</c>, <c>Email</c>, <c>Description</c> and <c>PhoneNumberIds</c>.</returns> public async Task <int> EditAsync(EditDepartmentServiceModel model) { Department department = this.dbContext.Departments.Find(model.Id); department.Name = model.Name; department.Email = model.Email; department.Description = model.Description; // First Remove departmentPhone related entity (Mapping table) for that department for (int i = 0; i < department.Phones.Count; i++) { this.dbContext.DepartmentPhones.Remove(department.Phones.ToArray()[i]); await this.dbContext.SaveChangesAsync(); i--; } // Then Add the new departmentPhone related entities (Mapping table) for that department with the new Phones foreach (var phoneNumberId in model.PhoneNumberIds) { await this.dbContext.DepartmentPhones.AddAsync(new DepartmentPhone { Department = department, PhoneId = phoneNumberId, }); } int modifiedEntities = await this.dbContext.SaveChangesAsync(); return(modifiedEntities); }
public async Task <IActionResult> Edit(DepartmentInputModel model) { if (!this.departmentsService.Exists(model.Id)) { return(this.BadRequest()); } if (!ModelState.IsValid) { return(this.RedirectToAction("Error", "Home")); } EditDepartmentServiceModel serviceModel = new EditDepartmentServiceModel { Id = model.Id, Name = model.Name, Email = model.Email, Description = model.Description, PhoneNumberIds = (model.PhoneNumberIds == null) ? new int[0] : model.PhoneNumberIds, }; await this.departmentsService.EditAsync(serviceModel); return(this.RedirectToAction("Details", "Departments", new { id = serviceModel.Id })); }