How to get the value of a property with Expression?

Asked

Viewed 61 times

1

I’m trying to get the value of a property through Expression, but I’m getting the following error.

The instance property '.Rota.Applicationname' is not defined for the guy 'System.Data.Entity.DynamicProxies.Filaraiz_93343013d3bb166e625f779b61fc319eeb1bbb98d8e88250da9549af70a0c8'

My implementation I’m trying to do is as follows.

private string ObterValorDoObjeto(Object obj, string propriedade)
{
    Expression propertyExpr = Expression.Property(
        Expression.Constant(obj),
        propriedade
    );

    return Expression.Lambda<Func<string>>(propertyExpr).Compile()();
}

And her call.

 var TemplateDeURI = ObterValorDoObjeto(fila, ".Rota.NomeDaAplicacao");

My object fila has a navigation object (Class) Rota who owns the property NomeDaAplicacao, and that’s the property I want to get value for,, but I’m not getting it.

  • Path is another class within the instance object type fila?

  • @Leandroangelo, that’s right public Rota Rota { get; set; }

  • I understand, you will need to make a recursion or reflection to navigate between the objects

1 answer

2


You can split the string and go through the array generating a Expression and passing itself as a parameter:

public static string ObterValorExp(object obj, string prop)
{
    string[] props = prop.Split('.');

    Expression exp = Expression.Property(Expression.Constant(obj), props[0]);

    for (int i = 1; i < props.Length; i++)
    {
          exp = Expression.Property(exp, props[i]);
    }

    return Expression.Lambda<Func<string>>(exp).Compile()();
}

I put in the .Netfiddle


You can also use Reflection, and with a recursive method go through the object until you get to the final property:

public static object ObterValor(object obj, string prop)
{
    string[] props = prop.Split('.');

    PropertyInfo pi = obj.GetType().GetProperty(props[0]);

    var xObj = pi.GetValue(obj, null);

    if (props.Length > 1)
    {
        string auxProp = String.Join(".", props,1, props.Length-1);
        return ObterValor(xObj, auxProp);
    }
    else
    {
        return xObj;
    }
}

See working on .Netfiddle

I did not make any error treatment, with more time I improve the code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.