首页 > 解决方案 > 按具有多对多关系的实体中的计数属性排序

问题描述

我正在使用 EfCore 3,并且我有一个具有多对多关系的实体,如下所示:

public class Foo
{
    ...
    public List<FooBar> FooBars { get; set; }
    public int BarsCount => FooBars.Count();
}

我想知道是否可以对其进行配置以使该查询起作用:

fooQuery.OrderBy(o => o.BarsCount)

现在我收到这个错误:

The LINQ expression 'DbSet<Foo>.OrderBy(d => d.BarsCount)' could not be translated. 
Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()

如果我.ToList()在调用OrderBy它之前使用 a ,但这不是一个好的解决方案,因为它会在我更改调用 Skip and Take 之前加载整个表。

标签: entity-frameworkentity-framework-core

解决方案


实体框架不知道如何将BarsCount属性转换为 SQL。因此,您需要使用完整的表达式:

var foos = context.Foos
    .OrderBy(d => d.FooBars.Count());

推荐阅读