简体   繁体   English

按匹配相关数据Linq的计数排序,ThenBy不起作用

[英]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.这在使用单个 OrderBy 时有效。

However, since I want to use Pagination, I need to use a ThenBy to make sure the order is always the same.但是,由于我想使用分页,我需要使用 ThenBy 来确保顺序始终相同。

The current query somehow moves the subquery inside the OrderBy/ThenBy and can't be translated.当前查询以某种方式将子查询移动到 OrderBy/ThenBy 内并且无法翻译。

How can I re-write this query so that ThenBy would work?如何重新编写此查询以便 ThenBy 可以工作?

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.而不是在构造函数中分配 Id 属性,而是在 PropertyDto 主体中分配 Id 属性和其他属性,类似于 MatchingContainsCount 属性。 EF core doesn't translate complex property assignment within the class constructor or methods to SQL. EF 核心不会将类构造函数或方法中的复杂属性分配转换为 SQL。 Only the simple assignments.只有简单的任务。 This should fix the problem.这应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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