DEV Community

Mahir Xalilov
Mahir Xalilov

Posted on

Example Servic+profile

INTERFACE
public interface ICategoryService
{
public Task AddCategoryAsync(AddCategoryDTO categoryDTO);
public Task> GetAllCategoriesAsync();
public Task> SelectAllCategoriesAsync();
public Task GetCategoryByIdAsync(int Id);
public Task UpdateCategoryAsync(UpdateCategoryDTO updateCategoryDTO);
public Task DeleteCategoryAsync(int Id);
}

IMPLEMENTATIONS

public class CategoryService : ICategoryService
{
readonly ICategoryRepository _repository;
readonly IMapper _mapper;
public CategoryService(IMapper mapper, ICategoryRepository repository)
{
_repository = repository;
_mapper = mapper;
}
public async Task AddCategoryAsync(AddCategoryDTO categoryDTO)
{
Category category = _mapper.Map(categoryDTO);
await _repository.AddAsync(category);
int result = await _repository.SaveChangesAsync();
if (result == 0)
{
throw new OperationNotValidException("Couldnt add category");
}
}

 public async Task DeleteCategoryAsync(int Id)
 {
     Category category = await _repository.GetByIdAsync(Id);
     _repository.Delete(category);
     int result = await _repository.SaveChangesAsync();
     if (result == 0)
     {
         throw new OperationNotValidException("Couldnt delete category");
     }
 }

 public async Task<ICollection<GetCategoryDTO>> GetAllCategoriesAsync()
 {
     ICollection<Category> categories = await _repository.GetAllAsync();
     ICollection<GetCategoryDTO> categoryDTOs = _mapper.Map<ICollection<GetCategoryDTO>>(categories);
     return categoryDTOs;
 }

 public async Task<GetCategoryDTO> GetCategoryByIdAsync(int Id)
 {
     Category category = await _repository.GetByIdAsync(Id);
     if (category is null)
     {
         throw new ItemNotFoundException("item not found.");
     }
     GetCategoryDTO categoryDTO = _mapper.Map<GetCategoryDTO>(category);
     return categoryDTO;
 }

 public async Task<ICollection<SelectListItem>> SelectAllCategoriesAsync()
 {
     return await _repository.SelectAllCategories();
 }

 public async Task UpdateCategoryAsync(UpdateCategoryDTO categoryDTO)
 {
     Category category = await _repository.GetByConditionAsync(c=>c.Id == categoryDTO.Id);
     if (category is null)
     {
         throw new ItemNotFoundException("item not found.");
     }

     Category updatedCategory = _mapper.Map<Category>(categoryDTO);
     _repository.Update(updatedCategory);
     int result = await _repository.SaveChangesAsync();
     if (result == 0)
     {
         throw new OperationNotValidException("Couldnt delete category");
     }
 }
Enter fullscreen mode Exit fullscreen mode

}

PROFILE
public class CategoryProfile : Profile
{
public CategoryProfile()
{
CreateMap().ReverseMap();
CreateMap().ReverseMap();
CreateMap().ReverseMap();
CreateMap().ReverseMap();
}
}

Top comments (0)