【发布时间】:2020-05-06 12:48:28
【问题描述】:
我正在尝试使用以下 efcore 查询按查询排序
获取需要排序的列的 PropertyInfo 通过使用下面的这个
var propertyInfo = typeof(TableVM).GetProperty("Type");
EfCore 查询
db.Table
**//LinkKit Extension Method**
.AsExpandable()
.Where(whereClause)
.Select(m => new TableVM
{
id= m.Id,
name = m.Name,
description = m.Description,
type = m.Type,
status = m.Status
})
**// Conversion of the OrderBy fails, which throws an exception saying it can't convert it into Linq query.**
.OrderBy(x => propertyInfo.GetValue(x, null))
.Skip(skip)
.Take(take)
.ToList();
C# - code to order by a property using the property name as a string
这适用于 EfCore 2。
在 EfCore 3.1.3 中删除了 LinqKit 扩展进行测试,它仅对 OrderBy 抛出错误,说明它无法将其转换为 Linq
我在 EfCore 查询中是否有任何错误?提前致谢
【问题讨论】:
-
EF 不知道如何将该代码转换为 SQL 查询,恐怕您不能像这样使用反射。 EF Core 2 会在日志中向您发出警告,然后在内存中而不是在数据库中完成所有操作。
-
不要使用链接中接受的答案,因为它不适用于
IQueryable。相反,请使用一些基于IQueryable/ 表达式的答案。 -
就像 Ivan 说的,不要使用那个,使用其他答案。
-
EF Core 2 并未将此类条件转换为 SQL,而是在从数据库中检索未过滤的数据后在内存中执行。所谓的客户端评估功能,在给您留下错误印象的同时对性能产生负面影响,因此在 EF Core 3.0+ 中已将其删除。这就是为什么现在您必须使用可翻译构造或显式切换到
IEnumerable方法。并且IQueryable/ 基于表达式的解决方案是可翻译的。 -
如果对您来说更容易,请从我的答案How to use a string to create a EF order by expression? 中获取代码。
标签: c# linq entity-framework-core