1

I have:

IQueryable<T> collection

var sortSelectorParameter = Expression.Parameter(typeof(T), "c");
var sortSelector = GetPropertyOrField<T>(sortSelectorParameter, "SomeId");

collection = collection.OrderByDescending(Expression.Lambda<Func<T, object>>(sortSelector, sortSelectorParameter));

This works fine if the parameter (SomeId) is a string. However if it's an integer (or presumably other types as well) then I get an exception saying it cannot convert int to an object.

If I try an Expression.Convert I get another exception later on saying entity framework cannot convert it to a string as it doesn't support conversions.

If I change Expression.Lambda<Func<T, object>> to Expression.Lambda<Func<T, int>> then it works perfectly but only for integer properties.

I am not sure how to make it support all types with some monstrous switch statement. Can anyone offer any advice on this?

NibblyPig
  • 51,118
  • 72
  • 200
  • 356
  • My guess would be related to Nullable objects and non-Nullable objects. Have you tried with ```int?``` instead of ```int```? – meneses.pt Apr 12 '17 at 16:46
  • Many thanks for finding the answer, it was a hard question to search for – NibblyPig Apr 12 '17 at 17:57
  • @NibblyPig You can't use `object` for the `TKey`. Use for example the response I gave you in your other question (http://stackoverflow.com/a/43369404/613130) that extract the key type and generates an `Expression<>` of the right type. – xanatos Apr 13 '17 at 06:16
  • And this is like your fifth question about `Expression<>` trees you do in 24h, trying to rebuild Dynamic Linq... [There is a perfect good source for Dynamic Linq, it is 2500 lines long and a single file](https://github.com/kahanu/System.Linq.Dynamic/blob/master/Src/System.Linq.Dynamic/DynamicLinq.cs). – xanatos Apr 13 '17 at 06:21

0 Answers0