CRUD stands for Create, Read, Update, and Delete. It is a set of basic operations commonly used in database and web development to manage data.
using FreshWebApp.Repository;
using FreshWebApp.Models;
using Dapper;
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>(SP.GetAllProducts);
return Ok(products);
}
// GET: api/Product/5
[HttpGet("{id}", Name = "GetProduct")]
public IActionResult
GetProductById(int id)
{
var parameter = new DynamicParameters();
parameter.Add("@Id", id);
var product =
_repository.OneRecord<Product>(SP.GetProductById, parameter);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
// POST: api/Product
[HttpPost]
public IActionResult
AddProduct(Product product)
{
var parameter = new DynamicParameters();
parameter.Add("@product",
product);
_repository.Execute(SP.AddProduct, parameter);
return CreatedAtRoute(SP.GetProductById, parameter);
}
// PUT: api/Product/5
[HttpPut("{id}")]
public IActionResult UpdateProduct(int id, Product product)
{
if (id != product.Id)
{
return BadRequest();
}
var parameter = new DynamicParameters();
parameter.Add("@product",
product);
_repository.Execute(SP.UpdateProduct, parameter);
return NoContent();
}
// DELETE: api/Product/5
[HttpDelete("{id}")]
public IActionResult DeleteProduct(int id)
{
var parameter = new DynamicParameters();
parameter.Add("@product",
product);
var existingProduct =
_repository.OneRecord<Product>(SP.DeleteProduct, parameter);
if (existingProduct == null)
{
return NotFound();
}
_repository.Execute(SP.DeleteProduct, parameter);
return NoContent();
}
}
}
namespace FreshWebApp.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
namespace FreshWebApp.Models
{
public static class SP
{
public const string UpdateProduct = "UpdateProduct";
public const string AddProduct = "AddProduct";
public const string GetAllProducts = "GetAllProducts";
public const string GetProductById = "GetProductById";
public const string DeleteProduct = "DeleteProduct";
}
}