分组到存储库 EF C# 中的泛型方法

  • 本文关键字:泛型方法 EF 存储 c#
  • 更新时间 :
  • 英文 :


我尝试在通用方法中进行分组,但是我尝试的方式给了我以下错误:

方法 'System.Linq.Enumerable.OrderBy 的类型参数 (System.Collections.Generic.IEnumerable , System.Func ('不能从用法中推断出来。尝试 显式指定类型参数。

通过该方法删除组可以正常工作,我唯一缺少的是使其可以分组。

public List<T> FilterPagerGroup<T, TType>(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, T>> select, int skip, int take, Expression<Func<TEntity, TType>> orderBy, Expression<Func<TEntity, TType>> groupBy)
    {
        List<T> result;
        result = EntitySet.Where(where).GroupBy(groupBy).OrderBy(orderBy).Skip(skip).Take(take).Select(select).ToList();
        return result;
    }

您正在对集合进行分组,因此您不再有IQueryable<TEntity>,您有IQueryable<IGrouping<TType, TEntity>>。您需要更新selectorderBy类型,以正确反映您正在执行的操作。下面是一个工作示例:

public class Thing<TEntity>
{
    public IQueryable<TEntity> EntitySet = new TEntity[0].AsQueryable();
    public List<T> FilterPagerGroup<T, TType>(
        Expression<Func<TEntity, bool>> where,
        Expression<Func<IGrouping<TType, TEntity>, T>> select, int skip, int take,
        Expression<Func<IGrouping<TType, TEntity>, TType>> orderBy,
        Expression<Func<TEntity, TType>> groupBy)
    {
        List<T> result;
        result = EntitySet.Where(where).GroupBy(groupBy).OrderBy(orderBy).Skip(skip).Take(take).Select(select).ToList();
        return result;
    }
}

请注意,此方法的调用方也需要更新以在IGrouping<TType, TEntity>上运行,而不是简单地TEntity

最新更新