Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

i don't think that there are other solutions

I managed to find one way myself, but it looks more of workaround, Marc's version is way more simpler. I will accept Marc's answer as soon as i will test 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 raw prototype, it should be more generic and not depend on DepartmentConsumption and without hardcoded "TotalPages"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top