0

I have a dynamic sort mechanism which I am using to do a dyanmic LINQ OrderBy. This works fine on ordinary fields.

string sortField = "MyField"
var orderByParam = Expression.Parameter(typeof(MyType), "MyType");
var sortExpression = Expression.Lambda<Func<MyType, object>>(Expression.Property(orderByParam, sortField), orderByParam);

However when I try to use a Nullable field (which happens to be a DateTime) I get the following error:

Expression of type 'System.Nullable`1[System.DateTime]' cannot be used for return type 'System.Object'

How can I get round this?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Rob Sedgwick
  • 4,342
  • 6
  • 50
  • 87
  • 1
    Have you tried using an `Expression.Convert` to cast the `DateTime?` to `object`? – Dirk Sep 05 '14 at 11:36

2 Answers2

2

You need to convert it to an object first. This has nothing to do with nullable field. I.E.:

string sortField = "MyField";
var orderByParam = Expression.Parameter(typeof(MyType), "MyType");
var sortExpression = Expression.Lambda<Func<MyType, object>>(
  Expression.Convert(Expression.Property(orderByParam, sortField), 
  typeof(object)), orderByParam);
Ondrej Svejdar
  • 21,349
  • 5
  • 54
  • 89
1

This is a dupe of Expression of type 'System.DateTime' cannot be used for return type 'System.Object' and Expression of type 'System.Int32' cannot be used for return type 'System.Object'

basically you cant do this for any value type (including nullable) as you need to explicitly box

see the accepted answer to the first link.

Community
  • 1
  • 1
tolanj
  • 3,651
  • 16
  • 30