Expression tree for a member access of depth > 1

巧了我就是萌 提交于 2019-12-04 21:48:24

You need:

var jobProperty = Expression.PropertyOrField(param, "Job");
var salaryProperty = Expression.PropertyOrField(jobProperty, "Salary");

Basically you're taking the Salary property from the result of evaluating x.Job.

If you need to do this in a programmatic way, you'll need something like:

Expression expression = Expression.Parameter(type, "x");
foreach (var property in properties.Split('.'))
{
    expression = Expression.PropertyOrField(expression, property);
}
Ivan

The best way will be create Extension as here:

public static class ExpressionExtensions
{
    /// <summary>
    ///     create expression by property name
    /// </summary>
    /// <typeparam name="TModel"></typeparam>
    /// <param name="propertyName">
    ///     <example>Urer.Role.Name</example>
    /// </param>
    /// <returns></returns>
    public static Expression<Func<TModel, dynamic>> CreateExpression<TModel>(this string propertyName) {
        Type currentType = typeof (TModel);
        ParameterExpression parameter = Expression.Parameter(currentType, "x");
        Expression expression = parameter;

        int i = 0;
        List<string> propertyChain = propertyName.Split('.').ToList();
        do {
            System.Reflection.PropertyInfo propertyInfo = currentType.GetProperty(propertyChain[i]);
            currentType = propertyInfo.PropertyType;
            i++;
            if (propertyChain.Count == i)
            {
                currentType = typeof (object);
            }
            expression = Expression.Convert(Expression.PropertyOrField(expression, propertyInfo.Name), currentType);
        } while (propertyChain.Count > i);

        return Expression.Lambda<Func<TModel, dynamic>>(expression, parameter);
    }
}

You cannot Convert() to typeof(object) everytime, because System.Object doesn't have property, that your type has (like Name or Salary in you example).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!