2

使用存储库模式时,有时您会在不同的存储库中出现相同的逻辑。在下面的示例中,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();
    }
}
4

2 回答 2

3

Rawling 提出的解决方案将起作用。另一种解决方案是提供在 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();
于 2012-10-19T08:36:08.973 回答
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();

但我对此有点模糊,所以试一试,看看它是否有效。

于 2012-10-19T08:22:49.010 回答