public interface IProductRepository : ICrudService{ // Additional methods specific to Product entity } public class EFProductRepository : IProductRepository { private readonly DbContext _context; public EFProductRepository(DbContext context) { _context = context; } public void Add(Product entity) { _context.Set ().Add(entity); } public void Delete(Product entity) { _context.Set ().Remove(entity); } public Product GetById(int id) { return _context.Set ().Find(id); } public void Update(Product entity) { _context.Entry(entity).State = EntityState.Modified; } }
[ApiController] [Route("[controller]")] public class ProductsController : ControllerBase { private readonly ICrudServiceIn this example, ProductsController is a RESTful API controller that uses the ICrudService interface to perform CRUD operations on the Product entity. The dependency injection of the ICrudService is provided through the constructor. HTTP methods such as POST, GET, PUT, and DELETE map to the corresponding CRUD operations using the ICrudService methods. Package/Library: The ICrudService interface is not tied to any specific package or library as it is a generic interface that can be implemented with various data access technologies. However, some popular libraries that use the CRUD operations and can work well with ICrudService include EntityFrameworkCore, Dapper, MongoDB.Driver, and LiteDB._productService; public ProductsController(ICrudService productService) { _productService = productService; } [HttpPost] public IActionResult Post(Product product) { _productService.Add(product); return CreatedAtAction(nameof(GetById), new { id = product.Id }, product); } [HttpGet("{id}")] public ActionResult GetById(int id) { var product = _productService.GetById(id); if (product == null) { return NotFound(); } return product; } [HttpPut("{id}")] public IActionResult Put(int id, Product product) { if (id != product.Id) { return BadRequest(); } _productService.Update(product); return NoContent(); } [HttpDelete("{id}")] public IActionResult Delete(int id) { var product = _productService.GetById(id); if (product == null) { return NotFound(); } _productService.Delete(product); return NoContent(); } }