0

I have A WishList Class , WishList Repository i want to decide whether to use OrderByDescending or OrderBy based on a parameter so i decided to write an extension methode as use it follow

 var notWorkingResult = _wishListRepository.GetAll()
                                    .GroupBy(x => x.ProductId)
                                    .Select(w => new TestDTo
                                    {
                                       Items = w.xOrderBy(orderByParam).Select(x => x.AddedDate.ToString()).ToList()
                                    }).ToList();

and here is my extension method

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));
}

the problem is the breakpoints not event hit the method i get the error

System.NotSupportedException: 'LINQ to Entities does not recognize the method 'System.Linq.IOrderedEnumerable1[Data.Wishlist] xOrderBy(System.Linq.IGrouping2[System.Guid,Data.Wishlist], System.String)' method, and this method cannot be translated into a store expression

i would appreciate any workaround on this

Arash
  • 3,458
  • 7
  • 32
  • 50

2 Answers2

1

You can do it by using System.Linq.Dynamic nuget package. Example:

myDataSource.OrderBy(columnName + " descending"); // for descending
myDataSource.OrderBy(columnName); // for ascending
Ceyhun
  • 1,354
  • 2
  • 10
  • 10
0

instead of an extension method, you can use the ternary operator:

Items = (orderByString == "desc" ? w.OrderByDescending(a => a.date) : w.OrderBy(a => a.date)).Select(x => x.AddedDate.ToString()).ToList() 
Joel Fleischman
  • 414
  • 2
  • 5