我需要添加一个扩展方法,该方法可以处理已存在的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);
*/
}
}
谢谢!
答案 0 :(得分:1)
我能想到的最简单的方法是使用param数组:
public IQueryable<TEntity> Include<TInclude>(params Expression<Func<TEntity, TInclude>>[] paths)
{
IQueryable<TEntity> results = _dbset;
paths.ToList().ForEach(x => results = results.Include(x));
return results
}