开发者

Eager loading of multiple related entities

开发者 https://www.devze.com 2023-04-11 00:41 出处:网络
I need to add an extension method that can handle multiple Include to an already existing Repository class:

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 开发者_StackOverflowEmployeeRepository : 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!


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号