entity-framework - 按具有多对多关系的实体中的计数属性排序
问题描述
我正在使用 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 之前加载整个表。
解决方案
实体框架不知道如何将BarsCount
属性转换为 SQL。因此,您需要使用完整的表达式:
var foos = context.Foos
.OrderBy(d => d.FooBars.Count());
推荐阅读
- jenkins - Jenkinsfile 中的变量范围
- ionic-framework - 使用链接分享我的对象 - ionic3
- ruby-on-rails-4 - 数据库列上的 Heroku 错误
- mongodb - 无法连接到 Dockerized MongoDb 服务器 - 绑定 ip - 没有机会授权
- javascript - Chartist.js 图表神器
- python - Django - Teplatetag "readmore" 想要成为 "readless"
- vb.net - 将此代码从 vb6 转换为 vb.net BigEndian 到整数
- c# - 动态扩展 XAML 窗口
- reactjs - 反应 Highcharts 错误
- javascript - UIkit 3 的过滤器组件:使用 URL 哈希设置活动过滤器 - 无法使用 JS 更改活动过滤器