I want to implement sorting objects by selected property.
Expression<Func<Goal, object>> sortProperty;
switch (sc.Sort)
{
case "Name":
sortProperty = p => p.Name; // String
break;
case "Priority":
sortProperty = p => p.Priority; // Enum
break;
case "CreatedDate":
sortProperty = p => p.CreatedDate; // DateTime
break;
case "Id":
default:
sortProperty = p => p.Id; // Long
break;
}
queryable = sc.IsAscending
? queryable.OrderBy(sortProperty)
: queryable.OrderByDescending(sortProperty);
When I materialize query by ToList method I get exception (in 'Id' scenario):
Additional information: Unable to cast the type 'System.Int64' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
My question is: is it possible to implement feature in such way? Or I should move chooseing between OrderBy and OrderByDescending to each case?