/// <exception cref="InvalidModelException"/> /// <exception cref="NotFoundException"/> public async Task <Guid> AddAsync(Dtos.Department dto) { var validator = new Dtos.DepartmentValidator(); ValidationResult result = validator.Validate(dto); if (!result.IsValid) { string errMess = string.Empty; foreach (var failure in result.Errors) { errMess += $"Property { failure.PropertyName } failed validation. Error was: { failure.ErrorMessage }\n"; } throw new InvalidModelException(errMess); } if (dto.StructuralUnitId != null && !await _context.Set <Entities.StructuralUnit>().AnyAsync(d => d.Id == dto.StructuralUnitId)) { throw new InvalidModelException($"Structural unit with id: {dto.StructuralUnitId} not found"); } var id = Guid.NewGuid(); var now = DateTime.UtcNow; var department = new Entities.Department { Code = dto.Code, Id = id, CreatedAt = now, UpdatedAt = now, Chief = dto.Chief, StructuralUnitId = dto.StructuralUnitId, FullName = dto.FullName, FullNameEng = dto.FullNameEng, ShortName = dto.ShortName }; await _context.AddAsync(department); await _context.SaveChangesAsync(); return(id); }
/// <exception cref="InvalidModelException"/> /// <exception cref="NotFoundException"/> public async Task UpdateAsync(Dtos.Department dto) { if (dto.Id.Equals(Guid.Empty)) { throw new InvalidModelException("Property Id failed validation. Error was: Id is empty"); } var validator = new Dtos.DepartmentValidator(); ValidationResult result = validator.Validate(dto); if (!result.IsValid) { string errMess = string.Empty; foreach (var failure in result.Errors) { errMess += $"Property { failure.PropertyName } failed validation. Error was: { failure.ErrorMessage }\n"; } throw new InvalidModelException(errMess); } if (!await _context.Set <Entities.StructuralUnit>().AnyAsync(d => d.Id == dto.StructuralUnitId)) { throw new InvalidModelException($"Structural unit with id: {dto.StructuralUnitId} not found"); } var department = await _context.FindAsync <Entities.Department>(dto.Id); if (department == null) { throw new NotFoundException($"Entity with id: {dto.Id} not found."); } department.Chief = dto.Chief; department.Code = dto.Code; department.FullName = dto.FullName; department.FullNameEng = dto.FullNameEng; department.ShortName = dto.ShortName; department.StructuralUnitId = dto.StructuralUnitId; department.UpdatedAt = DateTime.UtcNow; await _context.SaveChangesAsync(); }