0

I need to add an extension method that can handle multiple Include to an already existing Repository class:

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);
    }
}

The current implementation can only handle one related entity. I need to be able to eager load two or more related entites as well.

my entity class:

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; }
}

Where I will use it:

 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);
       */
    }
}

Thank you!

jdalino
  • 1
  • 2
  • possible duplicate of [EF Including Other Entities (Generic Repository pattern)](http://stackoverflow.com/questions/5376421/ef-including-other-entities-generic-repository-pattern) – Ladislav Mrnka Oct 05 '11 at 07:18

1 Answers1

1

The simplest way I can think of would be to use a param array:

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
} 
Smudge202
  • 4,689
  • 2
  • 26
  • 44