我需要向已经存在的 Repository 类添加一个可以处理多个 Include 的扩展方法:
public abstract class Repository<TEntity, TPrimaryKey> : IRepository<TEntity, TPrimaryKey>
where TEntity : class
{
private MyContext _dbContext;
private readonly DbSet<TEntity> _dbSet;
public IDatabaseFactory DatabaseFactory { get; private set; }
protected Repository(IDatabaseFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
_dbSet = Context.Set<TEntity>();
}
protected MyContext Context
{
get { return _dbContext ?? (_dbContext = DatabaseFactory.Get()); }
}
public IQueryable<TEntity> Include(Expression<Func<TEntity, object>> path)
{
return _dbSet.Include(path);
}
}
当前的实现只能处理一个相关实体。我还需要能够急切地加载两个或更多相关实体。
我的实体类:
public class Employee
{
public int EmployeeId { get; set; }
public virtual ICollection<Adjustment> Adjustments { get; set; }
public int? TotalAdjustmentsPerEmployeeId { get; set; }
public virtual TotalAdjustmentsPerEmployee TotalAdjustmentPerEmployee { get; set; }
}
我将在哪里使用它:
public class EmployeeRepository : Repository<Employee, int>, IEmployeeRepository
{
public EmployeeRepository(IDatabaseFactory databaseFactory) : base(databaseFactory)
{ }
public IEnumerable<Employee> GetAll(int companyID)
{
/**
* I need to load employees based on their companyID and eager load
* related TotalAdjustmentPerEmployee and Adjustments entities something like:
* return this.Include(a => a.TotalAdjustmentPerEmployee)
* .Include(a => a.Adjustments)
* .Where(e => e.CompanyId == companyID);
*/
}
}
谢谢!