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

I have code like

DepartmentPaperConsumption dto = null; 

then later I have the result of NHibernate QueryOver and I want to order it

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

but I want to be able to specify any dto property dynamically with a string. I tried using Dynamic LINQ , but it seems like I just can't get it. I also tried creating LambdaExpression from scratch - also with no luck. I would appreciate any help.

+4
source share
3 answers

You can see how to build lambda here , but in your case it is quite simple:

 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 difficult thing is calling OrderByAlias - using MakeGenericMethod can be a way, as shown in the link above.

+9
source

use dynamic linq, as you wrote, or use the expression tree http://msdn.microsoft.com/en-us/library/bb397951.aspx

I do not think there are other solutions

+3
source

I managed to find one way, but it looks more workaround, the Marc version is much simpler. I will answer Marc as soon as I try it. Heres my workaround:

 public class MemberModifier : ExpressionVisitor { public Expression Modify(Expression expression) { return Visit(expression); } protected override Expression VisitMember(MemberExpression node) { var t = typeof (DepartmentPaperConsumption); var memberInfo = t.GetMember("TotalPages")[0]; return Expression.MakeMemberAccess(node.Expression, memberInfo); } } 

and then in code

  Expression<Func<object>> exp = () => dto.TotalColorPrints; var mod = new MemberModifier(); var modEx = mod.Modify(exp); result.OrderByAlias((Expression<Func<object>>)modEx) 

MemberModifier is only an original prototype, it should be more general and independent of DepartmentConsumption and without hardcoded "TotalPages"

+2
source

Source: https://habr.com/ru/post/1337307/


All Articles