Ejemplo n.º 1
0
        public IActionResult UpdateEmployee(Guid EmpId, [FromBody] EmployeeForUpdateDto employee)
        {
            var employeeFromRepo = _appRepository.GetEmployee(EmpId);

            if (employeeFromRepo == null)
            {
                //Not found if you are stoppping upserting
                //else create and entity, save and return 201 createatroute
                //return NotFound();
                var employeeEntity = Mapper.Map <Employee>(employee);
                employeeEntity.EmpId = EmpId;

                if (!_appRepository.Save())
                {
                    throw new Exception($"Upserting of Employee with id {EmpId} failed on save.");
                }

                var employeeToReturn = Mapper.Map <EmployeeDto>(employeeEntity);

                return(CreatedAtRoute("GetEmployee", new { empId = employeeToReturn.EmpId }, employeeToReturn));
            }

            Mapper.Map(employee, employeeFromRepo);

            _appRepository.UpdateEmployee(employeeFromRepo);

            if (!_appRepository.Save())
            {
                throw new Exception($"Updation for Employee with id {EmpId} failed on save.");
            }

            return(NoContent());
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> UpdateEmployee(int Id, EmployeeForUpdateDto employee)
        {
            var employeeFromRepo = await _employeeRepo.GetEmployeeAsync(Id);

            if (employeeFromRepo == null)
            {
                return(NotFound());
            }

            var validationResults = new EmployeeForUpdateDtoValidator().Validate(employee);

            validationResults.AddToModelState(ModelState, null);

            if (!ModelState.IsValid)
            {
                return(BadRequest(new ValidationProblemDetails(ModelState)));
                //return ValidationProblem();
            }

            _mapper.Map(employee, employeeFromRepo);
            _employeeRepo.UpdateEmployee(employeeFromRepo);

            await _employeeRepo.SaveAsync();

            return(NoContent());
        }
Ejemplo n.º 3
0
        public IActionResult UpdateEmployeeForCompany(Guid companyId, Guid id, [FromBody] EmployeeForUpdateDto employee)
        {
            if (employee == null)
            {
                _logger.LogError("EmployeeForCreateDto Object sent from client is null");
                return(BadRequest("EmployeeForCreateDto Object is null"));
            }
            var company = _repositrory.Company.GetCompanyAsync(companyId, trackChanges: false);

            if (company == null)
            {
                _logger.LogInfo($"Company Wiht Id : {companyId} doesn't exist in the database");
                return(NotFound());
            }
            if (!ModelState.IsValid)
            {
                _logger.LogError("Invalid model state for the EmployeeForUpdateDto object");
                return(UnprocessableEntity(ModelState));
            }
            var employeeEntitiy = _repositrory.Employee.GetEmployee(companyId, id, trackChanges: true);

            if (employeeEntitiy == null)
            {
                _logger.LogInfo($"Employee Wiht Id : {id} doesn't exist in the database");
                return(NotFound());
            }
            _mapper.Map(employee, employeeEntitiy);
            _repositrory.SaveAsync();
            return(NoContent());
        }
Ejemplo n.º 4
0
        public IActionResult ApproveOrRejectEmployee(int id, [FromBody] EmployeeForUpdateDto employeeForUpdateDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var businessCard = _businessCardRepository.GetBusinessCard(employeeForUpdateDto.BusinessCardId);

            if (businessCard == null)
            {
                return(NotFound($"Business card with id {employeeForUpdateDto.BusinessCardId} was not found!"));
            }
            var company = _companyRepository.GetCompany(id);

            if (businessCard.User.Company == company && businessCard.User.EmployeeStatus == EmployeeStatus.NotApproved)
            {
                businessCard.User.EmployeeStatus = employeeForUpdateDto.Status;
                _managerRepository.UpdateEmployee(businessCard.User);
                if (_managerRepository.Save())
                {
                    return(NoContent());
                }
                else
                {
                    _logger.LogError($"Failed to update employee with user id {businessCard.User.Id} for company {company.Id}.");
                    return(StatusCode(500, "A problem happened while handling your request."));
                }
            }
            return(BadRequest());
        }
        private void MapRelatedCollectionOnPatch(EmployeeForUpdateDto employeeToPatch,
                                                 ref Employee employeeFromDb)
        {
            var employeeToPatchSkillIds = new HashSet <Guid>();

            employeeToPatch.EmployeeSkills.ToList().ForEach(es => employeeToPatchSkillIds.Add(es.SkillId));
            var employeeFromDbSkillIds = new HashSet <Guid>();

            employeeFromDb.EmployeeSkills.ToList().ForEach(es => employeeFromDbSkillIds.Add(es.Skill.Guid));

            if (!employeeToPatchSkillIds.SetEquals(employeeFromDbSkillIds))
            {
                employeeFromDb.EmployeeSkills.Clear();
                var mappedEmployeeSkills = new List <EmployeeSkill>();
                employeeToPatch.EmployeeSkills.ToList().ForEach(es => mappedEmployeeSkills.Add(new EmployeeSkill()
                {
                    SkillId = _unitOfWork.Skills.GetSkill(es.SkillId).Id
                }));

                foreach (var employeeSkill in mappedEmployeeSkills)
                {
                    employeeFromDb.EmployeeSkills.Add(employeeSkill);
                }

                employeeFromDb.UpdateSkillsetDate();
            }
        }
Ejemplo n.º 6
0
        public IActionResult UpdateEmployee(Guid companyId, Guid id, [FromBody] EmployeeForUpdateDto employee)
        {
            if (employee == null)
            {
                _logger.LogInfo("EmployeeForUpdateDto object sent from client is null");
                return(BadRequest("EmployeeForUpdateDto object is null"));
            }

            var company = _repository.Company.GetCompany(companyId, false);

            if (company == null)
            {
                _logger.LogInfo($"Company with id {companyId} doesn't exist in the database");
                return(NotFound());
            }

            var employeeEntity = _repository.Employee.GetEmployee(companyId, id, true);

            if (employeeEntity == null)
            {
                _logger.LogInfo($"Employee with id {id} doesn't exist in the database");
                return(NotFound());
            }
            _mapper.Map(employee, employeeEntity);
            _repository.Save();

            return(NoContent());
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> UpdateEmployeeForCompany([FromBody] EmployeeForUpdateDto employee)
        {
            var employeeEntity = HttpContext.Items["employee"] as Employee;

            _mapper.Map(employee, employeeEntity);
            await _repository.SaveAsync();

            return(NoContent());
        }
        public async Task <IActionResult> PartiallyUpdateEmployeeForCompany(Guid companyId, Guid id, [FromBody] JsonPatchDocument <EmployeeForUpdateDto> patchDoc)
        {
            if (patchDoc == null)
            {
                _logger.LogError("patchDoc object sent from client is null.");
                return(BadRequest("patchDoc object is null"));
            }

            var company = await _repository.Company.GetCompanyAsync(companyId, trackChanges : false);

            if (company == null)
            {
                _logger.LogInfo($"Company with id: {companyId} doesn't exist in the database.");
                return(NotFound());
            }

            var employeeEntity = await _repository.Employee.GetEmployeeAsync(companyId, id, trackChanges : true);

            if (employeeEntity == null)
            {
                _logger.LogInfo($"Employee with id: {id} doesn't exist in the database.");
                return(NotFound());
            }

            //var employeeToPatch = _mapper.Map<EmployeeForUpdateDto>(employeeEntity);
            var employeeToPatch = new EmployeeForUpdateDto
            {
                Name     = employeeEntity.Name,
                Age      = employeeEntity.Age,
                Position = employeeEntity.Position
            };

            patchDoc.ApplyTo(employeeToPatch, ModelState); //validating patchDoc (checks to see that paths are correct/exists)
            TryValidateModel(employeeToPatch);             //validates the values to make sure model is valid

            if (!ModelState.IsValid)
            {
                _logger.LogError("Invalid model state for the patch document");
                return(UnprocessableEntity(ModelState));
            }

            //saving employeeEntity to db
            //_mapper.Map(employeeToPatch, employeeEntity);
            employeeEntity.Name     = employeeToPatch.Name;
            employeeEntity.Age      = employeeToPatch.Age;
            employeeEntity.Position = employeeToPatch.Position;
            await _repository.SaveAsync();

            return(NoContent());
        }
        public IActionResult Put([FromBody] EmployeeForUpdateDto employeeForUpdateDto)
        {
            var result = _employeeService.Put(employeeForUpdateDto);

            if (result.Success)
            {
                return(Ok(result.Object));
            }

            if (!string.IsNullOrEmpty(result.Message))
            {
                return(BadRequest(new { error = result.Message }));
            }

            return(StatusCode(500));
        }
        public async Task<IActionResult> updateEmployee(int id, EmployeeForUpdateDto employeeForUpdateDto)
        {
            if (id != int.Parse(Employee.FindFirst(ClaimTypes.NameIdentifier).Value))
                return Unauthorized();

            var employeeFromRepo = await _repo.GetEmployee(id);


            _mapper.Map(employeeForUpdateDto, employeeFromRepo);

            if (await _repo.SaveAll())
                return NoContent();


            throw new Exception($"Updating user {id} failed on save");
        }
Ejemplo n.º 11
0
        public async Task <bool> UpdateAsync(Guid id, EmployeeForUpdateDto employeeForUpdate)
        {
            var employee = await _repositoryManager.Employee.GetEmployeeAsync(CurrentUserId, id);

            if (employee == null)
            {
                _logger.LogWarning("There is no employee with {Id}", id);
                return(false);
            }

            _mapper.Map(employeeForUpdate, employee);

            _repositoryManager.Employee.UpdateEmployee(employee);
            await _repositoryManager.SaveAsync();

            return(true);
        }
Ejemplo n.º 12
0
        public void UpdateEmployee_InValidInputNull_ReturnsBadRequestObjectResult()
        {
            // Arrange
            Employee employeeToUpdate = SeedTestData.GetTestEmployee();

            EmployeeForUpdateDto employeeForUpdateDto = null;

            var controller = new EmployeesController(mockRepo.Object, _mapper);
            // Act
            var result = controller.UpdateEmployee(employeeToUpdate.Id, employeeForUpdateDto);

            // Assert
            Assert.IsInstanceOf <BadRequestObjectResult>(result);

            mockRepo.Verify(repo => repo.Employee.GetEmployee(employeeToUpdate.Id, true), Times.Never);
            mockRepo.Verify(repo => repo.Save(), Times.Never);
        }
        public async Task <IActionResult> UpdateEmployee(int userId, int employeeId, EmployeeForUpdateDto employeeForUpdateDto)
        {
            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var employeeFromRepo = await _repo.GetEmployee(userId, employeeId);

            _mapper.Map(employeeForUpdateDto, employeeFromRepo);

            if (await _repo.SaveAll())
            {
                return(CreatedAtRoute("GetEmployee", new { employeeId = employeeFromRepo.Id, userId = userId }, employeeFromRepo));
            }

            throw new Exception($"Updating employee {employeeId} failed on save");
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> UpdateEmployee(int id, EmployeeForUpdateDto employeeForUpdateDto)
        {
            if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var employeeFromDb = await _context.GetEmployee(id);

            _mapper.Map(employeeForUpdateDto, employeeFromDb);

            if (await _context.SaveAll())
            {
                return(NoContent());
            }

            throw new System.Exception($"updating employee {id} failed on save.");
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> UpdateEmployee(int id, EmployeeForUpdateDto employeeForUpdateDto)
        {
            var employeeFromRepo = await _repo.GetEmployee(id);

            if (employeeFromRepo == null)
            {
                return(NotFound());
            }

            _mapper.Map(employeeForUpdateDto, employeeFromRepo);

            if (await _repo.SaveAll())
            {
                return(NoContent());
            }

            throw new Exception($"Updating employee {id} failed on save");
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> UpdateEmployee(int?id, EmployeeForUpdateDto employeeForUpdateDto)
        {
            if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var employeeFromRepo = await _repo.GetEmployee(id.Value);

            _mapper.Map(employeeForUpdateDto, employeeFromRepo);

            if (await _repo.SaveAll())
            {
                return(NoContent());
            }

            throw new Exception($"Updating employee {id.Value} faled on save");
        }
Ejemplo n.º 17
0
        public IActionResult UpdateEmployeeForCompany(Guid id, [FromBody] EmployeeForUpdateDto employee)
        {
            #region использование валидации

            /*Чтобы вернуть 422 вместо 400, первое, что нам нужно сделать, это подавить
             * BadRequest ошибка, когда ModelState является недействительным.
             * Мы собираемся сделать это, добавив этот код в Startup класс в ConfigureServices метод:
             * services.Configure<ApiBehaviorOptions>(options =>
             * {
             * options.SuppressModelStateInvalidFilter = true;
             * });
             */

            #endregion
            if (!ModelState.IsValid)
            {
                _logger.LogError("Invalid model state for the EmployeeForCreationDto object");
                return(UnprocessableEntity(ModelState));
            }

            if (employee == null)
            {
                _logger.LogError("EmployeeForUpdateDto object sent from client is null.");
                return(BadRequest("EmployeeForUpdateDto object is null"));
            }

            var companiesId = _wrapper.Company.
                              FindCompaniesWhithEmployeeQuer().
                              FirstOrDefault(x => x.Employees.Any(e => e.Id == id)).Id;

            var employeeEntity = _wrapper.Employee.GetEmployee(companiesId, id, trackChanges: true);

            if (employeeEntity == null)
            {
                _logger.LogInfo($"Employee with id: {id} doesn't exist in the database.");
                return(NotFound());
            }
            _mapper.Map(employee, employeeEntity);
            _wrapper.SaveAsync();

            return(NoContent());
        }
        public IActionResult UpdateEmployee(Guid employeeId, [FromBody] EmployeeForUpdateDto employeeDto)
        {
            if (employeeDto == null)
            {
                return(BadRequest("EmployeeForUpdateDto is empty"));
            }
            var employee = _repositoryManager.Employee.GetEmployee(employeeId, true);

            if (employee == null)
            {
                return(NotFound()); //404
            }
            employee.Name     = employeeDto.Name;
            employee.Age      = employeeDto.Age;
            employee.Position = employeeDto.Position;
            //ofwel met automapper://eerst aan MappingProfile toevoegen: CreateMap<EmployeeForUpdateDto, Employee>();//101
            // _mapper.Map(employeeDto, employee);
            _repositoryManager.Save();
            return(Ok(employee));
        }
Ejemplo n.º 19
0
        public IActionResult UpdateEmployee(Guid employeeId, [FromBody] EmployeeForUpdateDto employeeDto)
        {
            if (employeeDto == null)
            {
                BadRequest("EmployeeForUpdateDto is empty");
            }
            var employee = _repositoryManager.Employee.GetEmployee(employeeId, true); //moet op true staan

            if (employee == null)
            {
                NotFound(); //404
            }
            //ovwel manueel
            //employee.Name = employee.Name;
            //employee.Age = employeeDto.Age;
            //employee.Position = employeeDto.Position;
            //ofwel zelf ofwel met automapper
            _mapper.Map(employeeDto, employee);
            _repositoryManager.Save();
            return(Ok(employee));
        }
Ejemplo n.º 20
0
        public async Task <IActionResult> UpdateEmployee(Guid id, EmployeeForUpdateDto empUpdateDto)
        {
            if (id != empUpdateDto.Id)
            {
                return(BadRequest());
            }
            var empFromRepo = await _repoEmp.GetEmployee(id);

            if (empFromRepo == null)
            {
                BadRequest("Could not find employee");
            }

            _mapper.Map(empUpdateDto, empFromRepo);

            if (await _repo.SaveAll())
            {
                return(NoContent());
            }
            throw new Exception($"Updating employee {id} failed on save");
        }
Ejemplo n.º 21
0
        public void UpdateEmployee_ValidInput_ReturnsOkObjectResult_WithUpdatedEmployee()
        {
            // Arrange
            Employee employeeToUpdate = SeedTestData.GetTestEmployee();

            employeeToUpdate.Name     = "gewijzigde naam";
            employeeToUpdate.Age      = 25;
            employeeToUpdate.Position = "gewijzigde positie";

            EmployeeForUpdateDto employeeForUpdateDto = new EmployeeForUpdateDto
            {
                Name     = employeeToUpdate.Name,
                Age      = employeeToUpdate.Age,
                Position = employeeToUpdate.Position,
            };

            mockRepo.Setup(repo => repo.Employee.GetEmployee(employeeToUpdate.Id, true))
            .Returns(employeeToUpdate).Verifiable();
            mockRepo.Setup(repo => repo.Save()).Verifiable();

            var controller = new EmployeesController(mockRepo.Object, _mapper);

            //Act
            var result = controller.UpdateEmployee(employeeToUpdate.Id, employeeForUpdateDto);

            // Assert
            Assert.IsInstanceOf <OkObjectResult>(result);
            OkObjectResult okResult = result as OkObjectResult;

            Assert.IsInstanceOf <Employee>(okResult.Value);
            var updatedEmployee = okResult.Value as Employee;

            Assert.AreEqual(employeeToUpdate.Name, updatedEmployee.Name);
            Assert.AreEqual(employeeToUpdate.Age, updatedEmployee.Age);
            Assert.AreEqual(employeeToUpdate.Position, updatedEmployee.Position);
            mockRepo.Verify(repo => repo.Employee.GetEmployee(updatedEmployee.Id, true), Times.Once);
            mockRepo.Verify(repo => repo.Save(), Times.Once);
        }
        public ResponseObject <EmployeeForReadDto> Put(EmployeeForUpdateDto employeeForUpdateDto)
        {
            var departmentForCheckId = _departmentRepository.Get(employeeForUpdateDto.idDepartment);

            if (departmentForCheckId == null)
            {
                return(new ResponseObject <EmployeeForReadDto>(false, "Departamento inexistente"));
            }

            var employeeForCheckLogin = _employeeRepository.Get(employeeForUpdateDto.Login);

            if (employeeForCheckLogin != null && employeeForCheckLogin.Id != employeeForUpdateDto.Id)
            {
                return(new ResponseObject <EmployeeForReadDto>(false, "Login já cadastrado"));
            }

            if (employeeForUpdateDto.Access && _employeeRepository.CountAccess() > 10)
            {
                return(new ResponseObject <EmployeeForReadDto>(false, "Dismarque a opção acesso ao sistema! Limite excedido"));
            }

            var employeeForCheckId = _employeeRepository.Get(employeeForUpdateDto.Id);

            if (employeeForCheckId == null)
            {
                return(new ResponseObject <EmployeeForReadDto>(false, "Funcionário inexistente"));
            }

            var employeeForUpdate = _mapper.Map <Employee>(employeeForUpdateDto);

            _employeeRepository.Put(employeeForUpdate);
            var commit = _unityOfWork.Commit();

            return(commit
                ? new ResponseObject <EmployeeForReadDto>(true, obj: _mapper.Map <EmployeeForReadDto>(employeeForUpdate))
                : new ResponseObject <EmployeeForReadDto>(false));
        }
Ejemplo n.º 23
0
        public IActionResult UpdateEmployee(int id, [FromBody] EmployeeForUpdateDto employee)
        {
            try
            {
                if (employee == null)
                {
                    _logger.LogError("employee object sent from client is null.");
                    return BadRequest("employee object is null");
                }
                if (!ModelState.IsValid)
                {
                    _logger.LogError("Invalid employee object sent from client.");
                    return BadRequest("Invalid model object");
                }

                var employeeEntity = _repository.Employee.GetEmployeeById(id);
                if (employeeEntity == null)
                {
                    _logger.LogError($"employee with id: {id}, hasn't been found in db.");
                    return NotFound();
                }

                _mapper.Map(employee, employeeEntity);

                _repository.Employee.UpdateEmployee(employeeEntity);
                _repository.Save();

                return NoContent();

            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong inside UpdateEmployee action: {ex.InnerException.Message}");
                return StatusCode(500, "Internal server error");
            }
        }
Ejemplo n.º 24
0
        public async Task <IActionResult> UpdateEmployeeForCompany(Guid companyId, Guid id, [FromBody] EmployeeForUpdateDto employee)
        {
            //if (employee == null)
            //{
            //    _logger.LogError("EmployeeForUpdateDto object sent from client is null.");
            //    return BadRequest("EmployeeForUpdateDto object is null");
            //}

            //if (!ModelState.IsValid)
            //{
            //    _logger.LogError("Invalid model state for the EmployeeForUpdateDto object");
            //    return UnprocessableEntity(ModelState);
            //}

            //var company = await _repository.Company.GetCompanyAsync(companyId, trackChanges: false);
            //if (company == null)
            //{
            //    _logger.LogInfo($"Company with id: {companyId} doesn't exist in the database.");
            //    return NotFound();
            //}
            //var employeeEntity = await _repository.Employee.GetEmployeeAsync(companyId, id, trackChanges: true);
            //The trackChanges parameter is set to true for the employeeEntity. That’s because we want EF Core to track changes on this entity.
            //This means that as soon as we change any property in this entity, EF Core will set the state of that entity to Modified

            var employeeEntity = HttpContext.Items["employee"] as Employee;

            if (employeeEntity == null)
            {
                _logger.LogInfo($"Employee with id: {id} doesn't exist in the database.");
                return(NotFound());
            }
            _mapper.Map(employee, employeeEntity);
            await _repository.SaveAsync();

            return(NoContent());
        }
Ejemplo n.º 25
0
        public async Task <IActionResult> UpdateEmployeeForCompany(Guid companyId, Guid id, [FromBody] EmployeeForUpdateDto employee)
        {
            var company = await _repositoryManager.Company.GetCompanyAsync(companyId, trackChanges : false);

            if (company == null)
            {
                _logger.LogInfo($"Company with id: {companyId} doesn't exist in the database.");
                return(NotFound());
            }
            var employeeEntity = await _repositoryManager.Employee.GetEmployeeAsync(companyId, id, trackChanges : true);

            if (employeeEntity == null)
            {
                _logger.LogInfo($"Employee with id: {id} doesn't exist in the database.");
                return(NotFound());
            }
            _mapper.Map(employee, employeeEntity);
            await _repositoryManager.SaveAsync();

            return(NoContent());
        }
Ejemplo n.º 26
0
        public async Task <IActionResult> UpdateEmployeeForCompany(Guid companyId, Guid id, [FromBody] EmployeeForUpdateDto employee)
        {
            var employeeEntity = HttpContext.Items["employee"] as Employee;

            if (employeeEntity == null)
            {
                _logger.LogInfo($"Employee with id: {id} doesn't exist in the database.");
                return(NotFound());
            }

            _mapper.Map(employee, employeeEntity);
            await _repository.SaveAsync();

            return(NoContent());
        }
Ejemplo n.º 27
0
        public async Task <IActionResult> UpdateEmployeeForCompany(Guid companyId, Guid id, [FromBody] EmployeeForUpdateDto employee)
        {
            //if (employee == null)
            //{
            //    _logger.LogError("EmployeeForUpdateDto object sent from client is null.");
            //    return BadRequest("EmployeeForUpdateDto object is null");
            //}
            //if (!ModelState.IsValid)
            //{
            //    _logger.LogError("Invalid model state for the EmployeeForUpdateDto object");
            //    return UnprocessableEntity(ModelState);
            //}
            //var company = await _repositoryManager.Company.GetCompanyAsync(companyId, trackChanges:false);
            //if(company == null)
            //{
            //    _logger.LogInfo($"Company with id: {companyId} doesn't exist in the database.");
            //    return NotFound();
            //}
            //var employeeEntity = _repositoryManager.Employee.GetEmployee(companyId, id, trackChanges: true);
            //if(employeeEntity == null)
            //{
            //    _logger.LogInfo($"Employee with id: {id} doesn't exist in the database.");
            //    return NotFound();
            //}
            var employeeEntity = HttpContext.Items["employee"] as Employee;

            _mapper.Map(employee, employeeEntity);
            await _repositoryManager.SaveAsync();

            return(NoContent());
        }
        public async Task <IActionResult> PutEmployee(Guid id, [FromBody] EmployeeForUpdateDto employeeForUpdateDto)
        {
            var employee = await _employeeService.UpdateAsync(id, employeeForUpdateDto);

            return(employee ? NoContent() : NotFound());
        }
Ejemplo n.º 29
0
        public async Task <IActionResult> UpdateEmployeeForCompany(Guid companyId, Guid id, [FromBody]
                                                                   EmployeeForUpdateDto employee)
        {
            //validation of model done by validation filter

            //Action filter confirms if company and employee exist
            var employeeEntity = HttpContext.Items["employee"] as Employee;

            //map employee to entity and save
            _mapper.Map(employee, employeeEntity);
            await _repository.SaveAsync();

            return(NoContent());
        }
        public async Task <IActionResult> UpdateEmployeeForCompany(Guid companyId, Guid id, [FromBody] EmployeeForUpdateDto employee)
        {
            //------------- The commented code below is replaced by the ActionFilter called as an attribute above ----------

            //if (employee == null)
            //{
            //    _logger.LogError("EmployeeForUpdateDto object sent from client is null.");
            //    return BadRequest("EmployeeForUpdateDto object is null");
            //}

            //if (!ModelState.IsValid)
            //{
            //    _logger.LogError("Invalid model state for the EmployeeForUpdateDto object");
            //    return UnprocessableEntity(ModelState);
            //}

            var employeeEntity = HttpContext.Items["employee"] as Employee;

            //------------- The commented code below is replaced by the ActionFilter called as an attribute above ----------

            //var company = await _repository.Company.GetCompanyAsync(companyId, trackChanges: false);
            //if (company == null)
            //{
            //    _logger.LogInfo($"Company with id: {companyId} doesn't exist in the database.");

            //    return NotFound();
            //}

            //var employeeEntity = await _repository.Employee.GetEmployeeAsync(companyId, id, trackChanges: true);
            //if (employeeEntity == null)
            //{
            //    _logger.LogInfo($"Employee with id: {id} doesn't exist in the database.");

            //    return NotFound();
            //}

            //_mapper.Map(employee, employeeEntity);
            employeeEntity.Name     = employee.Name;
            employeeEntity.Age      = employee.Age;
            employeeEntity.Position = employee.Position;
            await _repository.SaveAsync();

            return(NoContent());
        }