在具有多对多关系的实体中,按计数属性排序



我正在使用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()

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

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

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

最新更新