简体   繁体   中英

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

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 错误 第2部分

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM