平均值 - EF通用存储库

时间:2018-05-29 07:36:56

标签: c# entity-framework generics

我想在我的实体框架通用存储库中添加计算平均值的方法。我能这样做真的很通用吗?我应该使用什么方法?这是我正在考虑的事情(这只是一个很好的例子作为起点)

    public double GetAverage(string property, Expression<Func<TEntity, bool>> filter = null) 
    {
        return BuildQuery(filter).Select(property).Average();
    }

或者做这个通用是个坏主意,我应该为特定实体创建特定的接口,其中的实现是明确的?

我的回购现在是

public interface IGenericRepository<TEntity> where TEntity : class
{
    void Delete(object id);
    void Delete(TEntity entityToDelete);

    TEntity GetFirst(Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "");

    IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "");

    PagedList<TEntity> GetPaged(int pageSize, int pageNumber, Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "");

    TEntity GetByID(object id);
    void Insert(TEntity entity);
    void Update(TEntity entityToUpdate);
    }

BuildQuery是:

private IQueryable<TEntity> BuildQuery(
    Expression<Func<TEntity, bool>> filter = null,
    Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
    string includeProperties = "")
{
    IQueryable<TEntity> query = _dbSet;

    if (filter != null)
    {
        query = query.Where(filter);
    }

    foreach (var includeProperty in includeProperties.Split
        (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
    {
        query = query.Include(includeProperty);
    }

    if (orderBy != null)
    {
        return orderBy(query);
    }
    else
    {
        return query;
    }
}

0 个答案:

没有答案