从通用资料档案库上的组中进行选择时转换Linq查询时出错

new9mtju  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(161)

我有下面的方法

public async Task<IList<TGroupSelect>> GetAll<TEntity,TGroup,TGroupSelect>(Func<IQueryable<T>, IIncludableQueryable<T, object>> include = null,
           Expression<Func<T, bool>> whereClause = null, Expression<Func<T, TEntity>> selector = null,

          Func<IQueryable<TEntity>, IQueryable<IGrouping<object, TEntity>>> groupBy = null,
          Func<IGrouping<object, TEntity>, TGroupSelect> groupSelector = null)
        {
            var result = _ctx.Set<T>().AsQueryable();

            result = include(result);

            var res = (whereClause is null ? result.Select(selector) : result.Where(whereClause).Select(selector));

           

            var group = groupBy(res);

            return  group.Select(groupSelector).ToList();
        }

在最后一次选择时,它抛出以下错误

The LINQ expression 'DbSet<UserMeetings>()
    .Include(x => x.User)
    .Include(x => x.Meeting)
    .ThenInclude(x => x.Host)
    .Where(x => x.UserId == __UserId_0)
    .Select(x => x)
    .GroupBy(y => y.Meeting)' 

could not be translated. Either rewrite the query in a form that can
 be translated, or switch to client evaluation explicitly by inserting
 a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or
 'ToListAsync'. 
See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

那么如何在不调用AsAsyncEnumerable的情况下使其在逐句分组后工作呢?
下面是我如何使用它

var meetings =await  repo.GetAll<UserMeetings,Meeting, IGrouping<Meeting, UserMeetings>> (
                include:x=>x.Include(x=>x.User).Include(x=>x.Meeting).ThenInclude(x=>x.Host),
                whereClause: filter,
                selector: x=>x,
                groupBy: x => { return x.GroupBy(x => x.Meeting); }, 
                groupSelector:(x)=> x);
cpjpxq1n

cpjpxq1n1#

根据.NET 5中的Microsoft文档,GroupBy不会转换为SQL查询,您应该在GroupBy语句之前使用AsEnumerableToList
您的代码应该如下所示:

public async Task<IList<TGroupSelect>> GetAll<TEntity,TGroup,TGroupSelect>(Func<IQueryable<T>, IIncludableQueryable<T, object>> include = null,
          Expression<Func<T, bool>> whereClause = null, Expression<Func<T, TEntity>> selector = null,
          Func<IQueryable<TEntity>, IQueryable<IGrouping<object, TEntity>>> groupBy = null,
          Func<IGrouping<object, TEntity>, TGroupSelect> groupSelector = null)
{
    var result = _ctx.Set<T>().AsQueryable();

    result = include(result);

    var res = await (whereClause is null 
               ? result.Select(selector) 
               : result.Where(whereClause).Select(selector)
             ).ToListAsync();

    var group = groupBy(res);

    return  group.Select(groupSelector).ToList();
}

相关问题