Implement initial product management with Entity Framework Core #3
This commit is contained in:
61
Api/Controllers/ProductController.cs
Normal file
61
Api/Controllers/ProductController.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Api.Models;
|
||||
|
||||
namespace Api.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class ProductController : ControllerBase
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public ProductController(AppDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
// GET: api/Product
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
|
||||
{
|
||||
return await _context.Products.ToListAsync();
|
||||
}
|
||||
|
||||
// POST: api/Product
|
||||
[HttpPost]
|
||||
public async Task<ActionResult<Product>> PostProduct([FromBody] Product product)
|
||||
{
|
||||
_context.Products.Add(product);
|
||||
await _context.SaveChangesAsync();
|
||||
return CreatedAtAction(nameof(GetProducts), new { id = product.Id }, product);
|
||||
}
|
||||
|
||||
// PUT: api/Product/{id}
|
||||
[HttpPut("{id}")]
|
||||
public async Task<IActionResult> PutProduct(int id, [FromBody] Product product)
|
||||
{
|
||||
if (id != product.Id)
|
||||
{
|
||||
return BadRequest();
|
||||
}
|
||||
_context.Entry(product).State = EntityState.Modified;
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
if (!await _context.Products.AnyAsync(e => e.Id == id))
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user