61 lines
1.8 KiB
C#
61 lines
1.8 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using BibliotecaAPI.Data;
|
|
using BibliotecaAPI.Models;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace BibliotecaAPI.Controllers
|
|
{
|
|
[Route("api/[controller]")]
|
|
[ApiController]
|
|
public class LibrosController : ControllerBase
|
|
{
|
|
private readonly BibliotecaContext _context;
|
|
|
|
public LibrosController(BibliotecaContext context)
|
|
{
|
|
_context = context;
|
|
}
|
|
|
|
[HttpGet]
|
|
public async Task<ActionResult<IEnumerable<Libro>>> GetLibros()
|
|
{
|
|
return await _context.Libros.ToListAsync();
|
|
}
|
|
|
|
[HttpGet("{id}")]
|
|
public async Task<ActionResult<Libro>> GetLibro(int id)
|
|
{
|
|
var libro = await _context.Libros.FindAsync(id);
|
|
if (libro == null) return NotFound();
|
|
return libro;
|
|
}
|
|
|
|
[HttpPost]
|
|
public async Task<ActionResult<Libro>> PostLibro(Libro libro)
|
|
{
|
|
_context.Libros.Add(libro);
|
|
await _context.SaveChangesAsync();
|
|
return CreatedAtAction(nameof(GetLibro), new { id = libro.IdLibro }, libro);
|
|
}
|
|
|
|
[HttpPut("{id}")]
|
|
public async Task<IActionResult> PutLibro(int id, Libro libro)
|
|
{
|
|
if (id != libro.IdLibro) return BadRequest();
|
|
_context.Entry(libro).State = EntityState.Modified;
|
|
await _context.SaveChangesAsync();
|
|
return NoContent();
|
|
}
|
|
|
|
[HttpDelete("{id}")]
|
|
public async Task<IActionResult> DeleteLibro(int id)
|
|
{
|
|
var libro = await _context.Libros.FindAsync(IdLibro);
|
|
if (libro == null) return NotFound();
|
|
_context.Libros.Remove(libro);
|
|
await _context.SaveChangesAsync();
|
|
return NoContent();
|
|
}
|
|
}
|
|
}
|