使用存储库模式时,有时您会在不同的存储库中出现相同的逻辑。在下面的示例中,EmployeeRepository中的GetTempEmployees ( )和 CompanyRepository中的 GetCompaniesWithTemps() 具有相同的表达式
e.IsTemp && e.IsDeleted == false
我的问题是最小化这种重复表达逻辑的推荐做法是什么。
例如。
public class Employee
{
public int EmployeeId { get; set; }
public bool IsTemp { get; set; }
public bool IsDeleted { get; set; }
}
public class Company
{
public int CompanyId { get; set; }
public bool IsDeleted { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
public class TestContext : DbContext
{
public TestContext()
{
}
public DbSet<Employee> Employee { get; set; }
public DbSet<Company> Company { get; set; }
}
public class EmployeeRepository
{
private readonly TestContext _context;
EmployeeRepository(TestContext context)
{
_context = context;
}
public ICollection<Employee> GetTempEmployees()
{
return _context.Employee.Where(e => e.IsTemp && e.IsDeleted==false).ToList();
}
}
public class CompanyRepository
{
private readonly TestContext _context;
CompanyRepository(TestContext context)
{
_context = context;
}
public ICollection<Company> GetCompaniesWithTemps()
{
return _context.Company.Where(c => c.Employees.Any(e => e.IsTemp && e.IsDeleted == false)).ToList();
}
}