score:8

Accepted answer

actually i don't think the problem has anything to do with nullable types, but rather with value types. try your method with a property of type decimal (not nullable<decimal>) : it will fail the same way.

have a look at how expression trees are generated for value and reference types (using linqpad for instance)

  • expression<func<t, object>> lambda = x => x.astring; (reference type)
    => the body is a memberexpression

  • expression<func<t, object>> lambda = x => x.adecimal; (value type)
    => the body is a unaryexpression with nodetype = convert and type = typeof(object), and its operand is a memberexpression

i modified your method slightly to take that into account, and it seems to work fine :

parameterexpression param = expression.parameter(typeof(t), "arg");

expression member = expression.property(param, propertyname);

if (member.type.isvaluetype)
{
  member = expression.convert(member, typeof(object));
}

return expression.lambda<func<t, object>>(member, param);

Related Query

More Query from same tag