معنديش في البروجكت حاجة اسمها Employee بس هنجرب بس عشان نتأكد ان الـ Design Pattern اللي اسمه Specification Design Pattern بيحقق الـ Open-Closed Principle
Models
هروح في الـ Models وأعمل Department و Employee
public class Department : BaseEntity
{
public string Name {get; set;}
public DateOnly DateOfCreation {get; set;}
}
public class Employee : BaseEntity
{
public string Name {get; set;}
public decimal Salary {get; set;}
public int? Age {get; set;}
// One (department) to Many (Employees)
public Department Department {get; set;}
}
Then
- المفروض دلوقتي أعمل Configuration لكل واحدة منهم واظبط الـ Relationship
- واعمل DbSet لكل واحدة
- واعمل Migration و Update و Seed
Controller
- نعمل Controller للـ Employee
- هيورث من الـ
BaseApiController
اللي احنا عاملينه - هنعمل ctor يعملي Object من الـ Generic Repository عشان أقدر أستخدم اللي جواها وأتعامل مع الـ Database من خلالها
- أروح في الـ Program أفعل الـ Dependency Injection (عشان أقدر أستخدم الـ Interface) فهنلاقينا عاملينها Assembly عن طريق الـ Reflection
public class EmployeesController : BaseApiController
{
private readonly IGenericRepository<Employee> _employeesRepo;
public EmployessController(IGenericRepository<Employee> employeesRepo)
{
_employeesRepo = employeesRepo;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Employee>>> GetEmployees()
{
//var spec = new ISpecification<Employee>();
// هعمل كلاس للإيمبلويي
var spec = new EmployeeWithDepartmentSpecifications();
var employees = await _employeesRepo.GetAllWithSpecAsync(spec);
}
}
Spec
في فولدر الـ Specifications في الـ Core، نعمل Folder نسميه Employee_Specs
public class EmployeeWithDepartmentSpecifications : BaseSpecifications<Employee>
{
// Critaria = null
public EmployeeWithDepartmentSpecifications()
: base()
{
Includes.Add(E => E.Department);
}
}
يبقا كدا الـ Base Specifications عبارة عن Container للـ Common code وهو Generic عشان هو بيشتغل مع أكتر من Entity