gpt4 book ai didi

c# - 在 linq 查询中设置动态排序名称字段

转载 作者:行者123 更新时间:2023-11-30 20:18:43 28 4
gpt4 key购买 nike

<分区>

我希望能够得到 OrderBy使用 lambda 表达式进行查询,以便我获得带有 TOP(n) 关键字的 SQL 查询(性能大幅提升)。

如果我指定......我能够做到这一点

PaginatedList = query.OrderBy(x => x.QuoteID).Skip(() => skipValue).Take(() => pageSize)

但是因为我希望 orderBy 字段通过名称的 UI 选择是动态的,所以我想做这样的事情:

var propertyInfo = typeof(Data.Quote).GetProperty(sortName);
Expression<Func<Data.Quote, object>> orderField = x => propertyInfo.GetValue(x, null);
PaginatedList = query.OrderBy(orderField).Skip(() => skipValue).Take(() => pageSize)

这给了我错误:

"LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object)' method, and this method cannot be translated into a store expression."

我试过这个不是 Expression<Func<T, object>> 类型的

var propertyInfo = typeof(Data.Quote).GetProperty(sortName);
Func<Data.Quote, object> orderField = x => propertyInfo.GetValue(x, null);
PaginatedList = query.OrderBy(x => orderField).Skip(() => skipValue).Take(() => pageSize)

我得到这个错误:

"Unable to create a constant value of type [...]. Only primitive types or enumeration types are supported in this context"

我确信有一种方法可以实现这一点,但目前不确定如何实现。

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com