public async Task <Role> GetByIdAsync(int id, CancellationToken cancellationToken = default) { var specFilter = new RoleFilterSpecification(id); var results = await _unitOfWork.RoleRepository.ListAsync(specFilter, null, cancellationToken); if (cancellationToken.IsCancellationRequested) { AddError("Cancellation requested"); return(null); } if (results?.Count > 0) { return(results[0]); } return(null); }
public async Task <ActionResult> UpdateItemAsync([FromBody] RoleDTO role, CancellationToken cancellationToken) { InitUserInfo(); var specFilter = new RoleFilterSpecification(role.Id); var rowCount = await _roleService.CountAsync(specFilter, cancellationToken); if (rowCount == 0) { throw new EntityNotFoundException(nameof(Role), role.Id); } // bind to old item var item = _mapper.Map <Role>(role); var result = await _roleService.UpdateAsync(item, cancellationToken); if (!result) { AssignToModelState(_roleService.Errors); return(ValidationProblem()); } return(CreatedAtAction(nameof(ItemByIdAsync), new { id = item.Id }, null)); }
public async Task <bool> UpdateAsync(Role entity, CancellationToken cancellationToken = default) { if (!ValidateBase(entity)) { return(false); } // update header AssignUpdater(entity); await _unitOfWork.RoleRepository.ReplaceAsync(entity, entity.Id, cancellationToken); // ambil old data var specFilter = new RoleFilterSpecification(entity.Id, true); var oldEntities = await _unitOfWork.RoleRepository.ListAsync(specFilter, null, cancellationToken); var oldEntity = oldEntities.FirstOrDefault(); List <RoleDetail> oldEntityToBeDeleted = new List <RoleDetail>(); if (oldEntity.RoleDetails.Count > 0) { foreach (var item in oldEntity.RoleDetails) { oldEntityToBeDeleted.Add(item); } } // smart update if (entity.RoleDetails.Count > 0) { foreach (var item in entity.RoleDetails) { var hasUpdate = false; if (oldEntity.RoleDetails.Count > 0) { var data = oldEntity.RoleDetails.SingleOrDefault(p => p.Id == item.Id); if (data != null) { AssignUpdater(item); await _unitOfWork.RoleDetailRepository.ReplaceAsync(item, item.Id, cancellationToken); oldEntityToBeDeleted.Remove(data); hasUpdate = true; } } if (!hasUpdate) { oldEntity.AddOrUpdateRoleDetail(item); } } } if (oldEntityToBeDeleted.Count > 0) { foreach (var item in oldEntityToBeDeleted) { oldEntity.RemoveRoleDetail(item); } } // update & commit await _unitOfWork.RoleRepository.UpdateAsync(oldEntity, cancellationToken); await _unitOfWork.CommitAsync(cancellationToken); return(true); }