Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build () => x.prop lambda expression dynamically?

I have code like

DepartmentPaperConsumption dto = null;

then later i have NHibernate QueryOver result, and i want to order it

result.OrderByAlias(() => dto.TotalColorCopys);

but I want to be able to specify any property of dto dynamicly with string. I tryed using Dynamic LINQ but is seems that I just can't get it. I also tried building LambdaExpression from ground up - also without luck. I would appreciate any help.

like image 322
Andrej Slivko Avatar asked Dec 06 '22 23:12

Andrej Slivko


1 Answers

You can see how to construct the lambda here, but it really is pretty simple in your case:

var arg = Expression.Constant(null, typeof(DepartmentPaperConsumption));
var body = Expression.Convert(Expression.PropertyOrField(arg, propertyName),
    typeof(object));
var lambda = Expression.Lambda<Func<object>>(body);

The tricky thing is invoking the OrderByAlias - using MakeGenericMethod may be the way, as shown in the link above.

like image 107
Marc Gravell Avatar answered Dec 09 '22 13:12

Marc Gravell