You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AdService.cs 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. namespace Diligent.WebAPI.Business.Services
  2. {
  3. public class AdService : IAdService
  4. {
  5. private readonly DatabaseContext _context;
  6. private readonly IMapper _mapper;
  7. public AdService(DatabaseContext context, IMapper mapper)
  8. {
  9. _context = context;
  10. _mapper = mapper;
  11. }
  12. public async Task<List<AdResponseDto>> GetAllAsync() =>
  13. _mapper.Map<List<AdResponseDto>>(await _context.Ads.ToListAsync());
  14. public async Task<AdResponseDto> GetByIdAsync(int id)
  15. {
  16. var ad = await _context.Ads.FindAsync(id);
  17. if(ad is null)
  18. throw new EntityNotFoundException("Ad not found");
  19. return _mapper.Map<AdResponseDto>(ad);
  20. }
  21. public async Task CreateAsync(AdCreateDto adCreateDto)
  22. {
  23. await _context.Ads.AddAsync(_mapper.Map<Ad>(adCreateDto));
  24. await _context.SaveChangesAsync();
  25. }
  26. public async Task UpdateAsync(int id, AdUpdateDto adUpdateDto)
  27. {
  28. var ad = await _context.Ads.FindAsync(id);
  29. if (ad is null)
  30. throw new EntityNotFoundException("Ad not found");
  31. _mapper.Map(adUpdateDto, ad);
  32. _context.Entry(ad).State = EntityState.Modified;
  33. await _context.SaveChangesAsync();
  34. }
  35. public async Task DeleteAsync(int id)
  36. {
  37. var ad = await _context.Ads.FindAsync(id);
  38. if (ad is null)
  39. throw new EntityNotFoundException("Ad not found");
  40. _context.Ads.Remove(ad);
  41. await _context.SaveChangesAsync();
  42. }
  43. }
  44. }