In a generic abstract base class, I store a couple of expressions used for ordering:
public Expression<Func<T, string>> OrderByString { get; set; } public Expression<Func<T, int>> OrderByInt { get; set; }
In the future, the base class is used:
if (OrderByString != null) { results = results.OrderBy(OrderByString); } else if (OrderByInt != null) { results = results.OrderBy(OrderByInt); }
Finally, one of them will be installed in the output of the constructor for a particular class:
this.OrderByString = c => c.CustomerID;
I do not like the fact that I need to have separate expressions based on the type of properties that I want for OrderBy. ToString will not work with this property because LINQ to Entities does not support it. What I need is a way to store an expression that selects any of the properties to order, regardless of type.
If I try something more general, for example:
public Expression<Func<T, object>> Order { get; set; }
Cannot enter type "System.Int32" to enter "System.Object". LINQ to Entities only supports listing of Entity Data Model primitive data types.
Also, if I try a little hack, this will not work either:
public Expression<Func<T, string>> Order { get; set; } this.Order = c => c.OrderID.ToString();
LINQ to Entities does not recognize the 'System.String ToString ()' method, and this method cannot be translated into the expression store.