CRUD operations are fundamental to database management and are commonly implemented in various software applications, including web applications, mobile apps, and desktop applications, to perform basic data manipulation tasks.
using FreshWebApp.Repository;
using FreshWebApp.Models;
namespace FreshWebApp.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductController :
ControllerBase
{
private readonly IRepositoryEF _repository;
public ProductController(IRepositoryEF
repository)
{
_repository =
repository;
}
// GET: api/Product
[HttpGet]
public IActionResult
GetAllProducts()
{
var products =
_repository.List<Product>("GetAllProducts");
return Ok(products);
}
// GET: api/Product/5
[HttpGet("{id}", Name = "GetProduct")]
public IActionResult
GetProductById(int id)
{
var product =
_repository.OneRecord<Product>("GetProductById", new { ProductId = id });
if (product == null)
{
return NotFound();
}
return Ok(product);
}
// POST: api/Product
[HttpPost]
public IActionResult
AddProduct(Product product)
{
_repository.Execute("AddProduct", new { product.Name, product.Price });
return CreatedAtRoute("GetProduct",
new { id =
product.Id }, product);
}
// PUT: api/Product/5
[HttpPut("{id}")]
public IActionResult UpdateProduct(int id, Product product)
{
if (id != product.Id)
{
return BadRequest();
}
_repository.Execute("UpdateProduct", new { product.Id, product.Name, product.Price });
return NoContent();
}
// DELETE: api/Product/5
[HttpDelete("{id}")]
public IActionResult DeleteProduct(int id)
{
var existingProduct = _repository.OneRecord<Product>("GetProductById",
new { ProductId
= id });
if (existingProduct == null)
{
return NotFound();
}
_repository.Execute("DeleteProduct", new { ProductId = id });
return NoContent();
}
}
}