//--------------- METHODS ----------------- /// <summary> /// Creates a new <see cref="Department"/> using the <see cref="CreateDepartmentServiceModel"/>. /// If such <see cref="Department"/> already exists in the database, fetches it's (int)<c>Id</c> and returns it. /// If such <see cref="Department"/> doesn't exist in the database, adds it and return it's (int)<c>Id</c>. /// </summary> /// <param name="model">Service model with <c>Name</c>, <c>Email</c>, <c>Description</c> and a collection of <c>Phones</c></param> /// <returns>Department ID</returns> public async Task <int> CreateAsync(CreateDepartmentServiceModel model) { int departmentId = this.dbContext.Departments.Where(x => x.Name == model.Name && x.Email == model.Email) .Select(x => x.Id) .FirstOrDefault(); if (departmentId != 0) // If departmentId is different than 0 (default int value), department with such name and email already exists, so return it's id. { return(departmentId); } Department department = new Department { Name = model.Name, Email = model.Email, Description = model.Description, }; foreach (var phoneDropdown in model.PhoneNumbers) { Phone phone = this.dbContext.Phones.FirstOrDefault(x => x.Id == phoneDropdown.Id); await this.dbContext.DepartmentPhones.AddAsync(new DepartmentPhone { Department = department, Phone = phone, }); } await this.dbContext.Departments.AddAsync(department); await this.dbContext.SaveChangesAsync(); return(department.Id); }
public async Task <IActionResult> Create(DepartmentInputModel model) { this.FillUnifiedModel(); if (!this.ModelState.IsValid) { return(this.View("Create", this.unifiedModel)); } var phones = new List <PhonesDropdownServiceModel>(); if (model.PhoneNumberIds != null) { foreach (int phoneNumberId in model.PhoneNumberIds) { phones.Add(new PhonesDropdownServiceModel { Id = phoneNumberId, }); } } var department = new CreateDepartmentServiceModel { Name = model.Name, Email = model.Email, Description = model.Description, PhoneNumbers = phones, }; await this.departmentsService.CreateAsync(department); return(this.RedirectToAction("Create")); }