0

我需要向已经存在的 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);
       */
    }
}

谢谢!

4

1 回答 1

1

我能想到的最简单的方法是使用参数数组:

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
} 
于 2011-10-05T06:30:56.347 回答