使用存储库模式时,有时您具有出现在不同存储库中的相同逻辑。在下面的示例中,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();
}
}
答案 0 :(得分:3)
我相信你必须使用Expression
,例如
static class EmployeeExpressions
{
public static System.Linq.Expressions.Expression<Func<Employee, bool>>
IsTempAndNotDeleted = e => e.IsTemp && !e.IsDeleted;
}
然后您可以将其用作
...
return _context.Employee
.Where(EmployeeExpressions.IsTempAndNotDeleted)
.ToList();
...
return _context.Company
.Where(c => c.Employees.Any(EmployeeExpressions.IsTempAndNotDeleted))
.ToList();
但我对此有点模糊,所以试一试,看看它是否有效。
答案 1 :(得分:3)
罗林提出的解决方案将起作用。另一种解决方案是提供在IQueryables上工作的扩展。类似的东西:
static class PersonSetExtensions
{
public static IQueryable<Person> WhereTempAndNotDeleted(this IQueryable<Person> set)
{
return set.Where(x => x.IsTemp && !x.IsDeleted);
}
}
可以在您的代码中使用:
return _context.Employee
.WhereTempAndNotDeleted()
.ToList();