How do I get the value of a property with Expression?

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 type   'System.Data.Entity.DynamicProxies.FilaRaiz_9328343013D3BB166E625F779B61FC319EEB1BBB98D8E88250DA9549AF70A0C8'

My implementation that 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 that has property NomeDaAplicacao , and this property I want to get the value , but I'm not getting it.

    
asked by anonymous 11.07.2018 / 20:52

1 answer

2

You can split the string and cycle through the array by 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 it in .NetFiddle

You can also use Reflection, and with a recursive method, go through the object until you reach 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 at .NetFiddle

I did not make any error handling, with more time I am improving the code

    
11.07.2018 / 22:39