Generic Repository

1. التعريف الأساسي للـ ProductsController

هنروح للـ Controller بتاعنا اللي احنا عملناه اللي هو بتاع ال Products كان المفروض أعمل Brands Repo , Category Repository بس مش هعمل كدا عشان مش محتاج Functionality زيادة ليهم فهنستخدم Generic Repository وهنكمل على الكود بتاع الـ Products Controller

public class ProductsController : BaseApiController
{
    private readonly IGenericRepository<Product> _productsRepo;
    private readonly IGenericRepository<ProductBrand> _brandsRepo;
    private readonly IGenericRepository<ProductCategory> _categoriesRepo;
 
    public ProductsController(
        IGenericRepository<Product> productsRepo,
        IGenericRepository<ProductBrand> brandsRepo,
        IGenericRepository<ProductCategory> categoriesRepo
    )
    {
        _productsRepo = productsRepo;
        _brandsRepo = brandsRepo;
        _categoriesRepo = categoriesRepo;
    }
 
    // Endpoints
}

2. إنشاء الـ Endpoints

2.1 Endpoint: GetBrands
  • الوصف: جلب جميع الـ Brands.
  • السبب لعدم استخدام Specification Design Pattern: الـ Brands لا تحتوي على Navigational Properties.
[HttpGet("brand")] // GET: /api/products/brands
public async Task<ActionResult<IEnumerable<ProductBrand>>> GetBrands()
{
    var brands = await _brandsRepo.GetAllAsync();
    return Ok(brands);
    // Not GetAllWithSpecAsync
}

مستخدمناش الـ Specification Design Pattern عشان هي مفيهاش Navigational Properties


2.2 Endpoint: GetCategories
  • الوصف: جلب جميع الـ Categories.
[HttpGet("categories")] // GET: /api/products/categories
public async Task<ActionResult<IEnumerable<ProductCategory>>> GetCategories()
{
    var categories = await _categoriesRepo.GetAllAsync();
    return Ok(categories);
}

3. استخدام IReadOnlyList في الـ Generic Repository

public interface IGenericRepository<T> where T : BaseEntity
{
    Task<T?> GetAsync(int id);
    Task<IReadOnlyList<T>> GetAllAsync();
    Task<IReadOnlyList<T>> GetAllWithSpecAsync(ISpecifications<T> spec);
    Task<T?> GetWithSpecAsync(ISpecifications<T> spec);
}
// Don't Forget to change the class too [Generic Repository Class]
// And don't change all IEnumerable in Product Controller
  • ملحوظة: يتم استبدال جميع IEnumerable بـ IReadOnlyList في الـ Generic Repository.

ملخص

  1. تم إنشاء ProductsController مع حقن Generic Repository للـ Products, Brands, و Categories.
  2. تعريف الـ Endpoints:
    • الـGetBrands: لإرجاع جميع الـ Brands بدون استخدام Specification Design Pattern.
    • الـGetCategories: لإرجاع جميع الـ Categories.
  3. تعديل الـ Generic Repository لاستخدام IReadOnlyList لتحسين الأداء ومنع التعديلات على البيانات.