Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using AutoMapper;
- using Microsoft.AspNetCore.Mvc;
- using _1._1._4._3___Pokemon_Review_Application.Data;
- using _1._1._4._3___Pokemon_Review_Application.Models;
- [Route("api/[controller]")]
- [ApiController]
- public abstract class BaseController<TEntity, TRepository, TDto> : ControllerBase
- where TEntity : class, IModelEntity
- where TRepository : IRepository<TEntity>
- where TDto : class
- {
- protected readonly TRepository _repository;
- protected readonly IMapper _mapper;
- public BaseController(TRepository repository, IMapper mapper)
- {
- _repository = repository;
- _mapper = mapper;
- }
- // GET: api/[controller]
- [HttpGet]
- public async Task<ActionResult<IEnumerable<TDto>>> Get()
- {
- var items = await _repository.GetAll();
- var dtoItems = _mapper.Map<IEnumerable<TDto>>(items);
- return Ok(dtoItems);
- }
- // GET: api/[controller]/5
- [HttpGet("{id}")]
- public async Task<ActionResult<TDto>> Get(int id)
- {
- var item = await _repository.Get(id);
- if (item == null)
- {
- return NotFound();
- }
- var dtoItem = _mapper.Map<TDto>(item);
- return Ok(dtoItem);
- }
- // PUT: api/[controller]/5
- [HttpPut("{id}")]
- public async Task<IActionResult> Put(int id, TDto dto)
- {
- var entity = _mapper.Map<TEntity>(dto);
- entity.Id = id;
- if (id != entity.Id)
- {
- return BadRequest();
- }
- await _repository.Update(entity);
- return NoContent();
- }
- // POST: api/[controller]
- [HttpPost]
- public async Task<ActionResult<TDto>> Post(TDto dto)
- {
- var entity = _mapper.Map<TEntity>(dto);
- await _repository.Add(entity);
- var createdDto = _mapper.Map<TDto>(entity);
- return CreatedAtAction("Get", new { id = entity.Id }, createdDto);
- }
- // DELETE: api/[controller]/5
- [HttpDelete("{id}")]
- public async Task<ActionResult<TDto>> Delete(int id)
- {
- var entity = await _repository.Delete(id);
- if (entity == null)
- {
- return NotFound();
- }
- var dto = _mapper.Map<TDto>(entity);
- return dto;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement