I realize this question has been asked many times, but there doesn't seem to be an updated answer using plain old reflection. I am trying to implement sorting into a WebAPI method by using reflection to retrieve the property sent in the "sortBy" parameter. Then I would like to call OrderBy or OrderByDescending according to the value of the "sortOrder" parameter.
Is using a lambda extension method the only way to achieve sorting by a property dynamically?
The accepted answer on this post had a really easy way of retrieving the property dynamically and then getting the value in the OrderBy/OrderByDescending call: How do I specify the Linq OrderBy argument dynamically?
However, this does not seem to work in .NET 6... It errors out and say it either can't be translated unless switched to client evaluation using an enumerable type or can't be cast when adding "AsEnumerable()" to the call.
//Sort products by user provided query
if (!string.IsNullOrEmpty(queryParameters.SortBy))
{
if(typeof(Product).GetProperty(queryParameters.SortBy) != null)
{
//Use reflection to get the sortBy property
var productPropInfo = typeof(Product).GetProperty(queryParameters.SortBy);
switch (queryParameters.SortOrder)
{
case "desc":
//Can't be translated
products = products.OrderByDescending(p => productPropInfo.GetValue(p));
break;
default:
//Can't be cast when explicitly casting or using AsQueryable()
products = products.AsEnumerable().OrderBy(p => productPropInfo.GetValue(p)).AsQueryable();
break;
}
}
}
Am I missing something? Or do I need to use a lambda extension method like in the link above?
NOTE: I am using an in memory database and Entity Framework Core
Thanks!