Home > Enterprise >  Sorting by count of matching related data Linq, ThenBy doesnt work
Sorting by count of matching related data Linq, ThenBy doesnt work

Time:06-26

I wrote a query that sorts the result based on the amount of matching elements of a given list. This works when using a single OrderBy.

However, since I want to use Pagination, I need to use a ThenBy to make sure the order is always the same.

The current query somehow moves the subquery inside the OrderBy/ThenBy and can't be translated.

How can I re-write this query so that ThenBy would work?

Thanks.

Code:

    products
        .Select(product => new ProductDto(product)
        {
            MatchingContainsCount = (from contain in product.Contains
                where allergens.Contains(contain.Allergen.Name)
                select contain.Allergen).Count(),
            MatchingMayContainCount = (from mayContain in product.MayContain
                where allergens.Contains(mayContain.Allergen.Name)
                select mayContain.Allergen).Count()
        })
        .OrderBy(dto => dto.MatchingContainsCount)
        .ThenBy(dto => dto.Id); // Without this line it works

The Translation error: linq error part2

CodePudding user response:

Instead assigning Id property inside the constructor, assign the Id property and other properties within the PropertyDto body, similar to MatchingContainsCount property. EF core doesn't translate complex property assignment within the class constructor or methods to SQL. Only the simple assignments. This should fix the problem.

  • Related