我正在使用规范查询搜索方法,它包括搜索、orderBy、groupBy。Search 和 Orderby 都可以,但我在这一行的 groupBy 方法中遇到了问题query.GroupBy(spec.GroupBy).SelectMany(x => x)
请看以下代码:
public async Task<PaginatedResult<List<EmployeeTypeResponse>>> Handle(GetAllEmployeeTypesQuery request, CancellationToken cancellationToken)
{
var employeeTypesWithPaging = _employeeTypeRepository.FindWithSpecificationPattern(new EmployeeTypeSpecifcation(request.Filter, true), true);
我想在 ApplyGroupBy(x => x.ShopId); 处使用 ShopId 申请 groupBy
public class EmployeeTypeSpecifcation : BaseSpecifcation<EmployeeType>
{
public EmployeeTypeSpecifcation()
{
}
public EmployeeTypeSpecifcation(PaginationFilter Filter, bool isPaging)
{
if (!string.IsNullOrEmpty(Filter.GroupBy))
{
ApplyGroupBy(x => x.ShopId);
}
var predicate = PredicateBuilder.True<EmployeeType>();
if (!string.IsNullOrEmpty(Filter.SearchText))
{
predicate = predicate.And(x => x.Name.Contains(Filter.SearchText) || x.Code.Contains(Filter.SearchText));
}
if (Filter.ShopId != null)
{
predicate = predicate.And(c => c.ShopId == Filter.ShopId);
}
}
}
像这样的 BaseSpecifcation 类
public class BaseSpecifcation<T> : ISpecification<T>
{
public BaseSpecifcation()
{
}
public BaseSpecifcation(Expression<Func<T, bool>> criteria)
{
Criteria = criteria;
}
public Expression<Func<T, object>> OrderBy { get; private set; }
public Expression<Func<T, object>> OrderByDescending { get; private set; }
public Expression<Func<T, object>> GroupBy { get; private set; }
protected virtual void ApplyGroupBy(Expression<Func<T, object>> groupByExpression)
{
GroupBy = groupByExpression;
}
protected void AddOrderBy(Expression<Func<T, object>> orderByExpression)
{
OrderBy = orderByExpression;
}
protected void AddOrderByDescending(Expression<Func<T, object>> orderByDescExpression)
{
OrderByDescending = orderByDescExpression;
}
}
FindWithSpecificationPattern 和 GetQuery 方法:
public IEnumerable<T> FindWithSpecificationPattern(ISpecification<T> specification = null, bool isPaging = false)
{
return SpecificationEvaluator<T>.GetQuery(DbContext.Set<T>().AsQueryable(), specification, isPaging);
}
public class SpecificationEvaluator<TEntity> where TEntity : class
{
public static IQueryable<TEntity> GetQuery(IQueryable<TEntity> inputQuery, ISpecification<TEntity> spec, bool isPaging)
{
var query = inputQuery;
if (spec.Criteria != null)
{
query = query.Where(spec.Criteria);
}
if (spec.GroupBy != null)
{
query = query.GroupBy(spec.GroupBy).SelectMany(x => x);
}
}
}
我在这条线上遇到了问题
query = query.GroupBy(spec.GroupBy).SelectMany(x => x);
虽然它不会抛出异常,但我无法得到结果。当我调试时,我看到错误消息
Query='((Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable<Nail.Management.Domain.Entities.Catalog.EmployeeType>)query).DebugView.Query' 引发了“System.InvalidOperationException”类型的异常
我在 Google 中搜索了很多次,但没有看到任何使用规范模式实现 GroupBy 的示例。请帮帮我,非常感谢!