We wrote a generic filterable repository in .NET 8 that should be able to accept a list of filters and a list of sorts, and apply them to any given entity.
Due to some business logic, we have a Task entity that needs to be grouped everytime it is filtered. The grouping ‘eats’ the sorts, and they never get applied, I checked the query that is executed. But we need to sort after the grouping, and then apply pagination.
The method looks like this:
public static (IQueryable Queryable, int TotalElements) BuildFilteredQuery(IQueryable queryable, List<FilterData> filters, List<SortData> sorts, int pageNo, int pageSize, bool distinct)
{
queryable = ApplyFilters(queryable, filters);
queryable = ApplySorting(queryable, sorts);
if (distinct)
{
queryable = queryable.GroupBy("new(CountSort)").Select("it.First()");
}
var totalElements = queryable.Count();
if (pageSize != 0)
{
queryable = ApplyPaging(queryable, pageNo, pageSize);
}
return (queryable, totalElements);
}
private static IQueryable ApplySorting(IQueryable queryable, List<SortData> sorts)
{
var sortingString = string.Join(", ", sorts.Select(s =>
$"{s.PropertyName} {(s.Direction == ListSortDirection.Ascending ? "asc" : "desc")}"));
if (!string.IsNullOrWhiteSpace(sortingString))
{
queryable = queryable.OrderBy(sortingString);
}
return queryable;
}
If we try to apply the sorting after the grouping, we get “The given key ‘EmptyProjectionMember’ was not present in the dictionary”.