In a generic abstract base class I'm storing a couple of expressions used for ordering:
public Expression<Func<T, string>> OrderByString { get; set; }
public Expression<Func<T, int>> OrderByInt { get; set; }
The get used later on in the generic base class:
if (OrderByString != null)
{
results = results.OrderBy(OrderByString);
}
else if (OrderByInt != null)
{
results = results.OrderBy(OrderByInt);
}
Finally one of them will get set in the deriving concrete class's constructer:
this.OrderByString = c => c.CustomerID;
I don't like the fact that I need to have separate expressions based on the property type I want to OrderBy. ToString won't work on the property's because LINQ to Entities doesn't support it. What I'm after is a way of storing an expression that picks any of the properties to order on regardless of type.
If I try something a little more generic such as:
public Expression<Func<T, object>> Order { get; set; }
Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ
to Entities only supports casting Entity Data Model primitive types.
Additionally if I try a slight hack this also doesn't work:
public Expression<Func<T, string>> Order { get; set; }
this.Order = c => c.OrderID.ToString();
LINQ to Entities does not recognize the method 'System.String
ToString()' method, and this method cannot be translated into a store
expression.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…