首页 > 解决方案 > 在 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.IGrouping2[System.Guid,Data.Wishlist], System.String)' 方法,并且此方法无法转换为存储表达式

我将不胜感激任何解决方法

标签: c#entity-frameworklinq

解决方案


您可以使用System.Linq.Dynamic nuget 包来完成。例子:

myDataSource.OrderBy(columnName + " descending"); // for descending
myDataSource.OrderBy(columnName); // for ascending

推荐阅读