Advertisement
Guest User

Untitled

a guest
Dec 9th, 2023
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.24 KB | None | 0 0
  1. using AutoMapper;
  2. using Microsoft.AspNetCore.Mvc;
  3.  
  4. using _1._1._4._3___Pokemon_Review_Application.Data;
  5. using _1._1._4._3___Pokemon_Review_Application.Models;
  6.  
  7.  
  8. [Route("api/[controller]")]
  9. [ApiController]
  10. public abstract class BaseController<TEntity, TRepository, TDto> : ControllerBase
  11.     where TEntity : class, IModelEntity
  12.     where TRepository : IRepository<TEntity>
  13.     where TDto : class
  14. {
  15.     protected readonly TRepository _repository;
  16.     protected readonly IMapper _mapper;
  17.  
  18.     public BaseController(TRepository repository, IMapper mapper)
  19.     {
  20.         _repository = repository;
  21.         _mapper = mapper;
  22.     }
  23.  
  24.     // GET: api/[controller]
  25.     [HttpGet]
  26.     public async Task<ActionResult<IEnumerable<TDto>>> Get()
  27.     {
  28.         var items = await _repository.GetAll();
  29.         var dtoItems = _mapper.Map<IEnumerable<TDto>>(items);
  30.         return Ok(dtoItems);
  31.     }
  32.  
  33.     // GET: api/[controller]/5
  34.     [HttpGet("{id}")]
  35.     public async Task<ActionResult<TDto>> Get(int id)
  36.     {
  37.         var item = await _repository.Get(id);
  38.         if (item == null)
  39.         {
  40.             return NotFound();
  41.         }
  42.  
  43.         var dtoItem = _mapper.Map<TDto>(item);
  44.         return Ok(dtoItem);
  45.     }
  46.  
  47.     // PUT: api/[controller]/5
  48.     [HttpPut("{id}")]
  49.     public async Task<IActionResult> Put(int id, TDto dto)
  50.     {
  51.         var entity = _mapper.Map<TEntity>(dto);
  52.         entity.Id = id;
  53.  
  54.         if (id != entity.Id)
  55.         {
  56.             return BadRequest();
  57.         }
  58.  
  59.         await _repository.Update(entity);
  60.         return NoContent();
  61.     }
  62.  
  63.     // POST: api/[controller]
  64.     [HttpPost]
  65.     public async Task<ActionResult<TDto>> Post(TDto dto)
  66.     {
  67.         var entity = _mapper.Map<TEntity>(dto);
  68.  
  69.         await _repository.Add(entity);
  70.  
  71.         var createdDto = _mapper.Map<TDto>(entity);
  72.         return CreatedAtAction("Get", new { id = entity.Id }, createdDto);
  73.     }
  74.  
  75.     // DELETE: api/[controller]/5
  76.     [HttpDelete("{id}")]
  77.     public async Task<ActionResult<TDto>> Delete(int id)
  78.     {
  79.         var entity = await _repository.Delete(id);
  80.  
  81.         if (entity == null)
  82.         {
  83.             return NotFound();
  84.         }
  85.  
  86.         var dto = _mapper.Map<TDto>(entity);
  87.         return dto;
  88.     }
  89. }
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement