c# - 在 Linq To EF 中动态决定 orderBy 和 orderByDescing
问题描述
我有一个 WishList 类,WishList 存储库我想根据参数决定是使用OrderByDescending还是 OrderBy,所以我决定编写一个扩展方法,如下使用它
var notWorkingResult = _wishListRepository.GetAll()
.GroupBy(x => x.ProductId)
.Select(w => new TestDTo
{
Items = w.xOrderBy(orderByParam).Select(x => x.AddedDate.ToString()).ToList()
}).ToList();
这是我的扩展方法
public static IOrderedEnumerable<Wishlist> xOrderBy(this IGrouping<Guid, Wishlist> source, string OrderBy)
{
if (OrderBy == "asc") return (source.OrderBy(x => x.AddedDate));
if (OrderBy == "desc") return (source.OrderByDescending(x => x.AddedDate));
//default order by
return (source.OrderBy(x => x.AddedDate));
}
问题是断点不是事件命中我得到错误的方法
System.NotSupportedException: 'LINQ to Entities 无法识别方法 'System.Linq.IOrderedEnumerable
1[Data.Wishlist] xOrderBy(System.Linq.IGrouping
2[System.Guid,Data.Wishlist], System.String)' 方法,并且此方法无法转换为存储表达式
我将不胜感激任何解决方法
解决方案
您可以使用System.Linq.Dynamic nuget 包来完成。例子:
myDataSource.OrderBy(columnName + " descending"); // for descending
myDataSource.OrderBy(columnName); // for ascending
推荐阅读
- sql - 使用 postgresql 连接一对多表时如何使用 LIMIT 和 OFFSET?
- python - 从 Python3.6 升级到 3.8 后 Pip、NumPy 和 Pytorch 消失了
- list - 有序列表的最小存储空间
- r - 错误:`position_jitterdodge()` 需要至少一种审美才能躲避
- android - Android Coroutines - 我如何等待两个不同的改造调用并将两个结果包装到一个 observable 中?
- apache-spark - Spark窗口函数并在每个分区的每列中获取第一个和最后一个值(窗口聚合)
- linkedin - LinkedIn API - 从广告帐户访问帐单交易/收据
- java - 如何在 RecyclerView 中突出显示竞争可见的项目视图
- sql - 如何在 SQL 中计算出现次数
- python-3.x - 启用气流身份验证会导致连接到主机出现问题