Search code examples
c#.netreflectionsystem.reflection

Getting model type from expression


I'm trying to use reflection to get the model type. So far I was able to get the type of property. But when I tried to use expression to get model type, I'm getting null reference for that property.

expression is like this,

model => model.property

and in function,

//I'm passing model as a parameter
MemberExpression expBody = expression.Body as MemberExpression;
model.GetType().GetProperty(expBody.Member.Name.ToString()));

Is it possible to do something like this?

MemberExpression expBody = expression.Body as MemberExpression;
    expBody.Type.GetProperty(expBody.Member.Name.ToString()));

I tried this, but not working.


Solution

  • If we assume that your expression is a lambda expression whose parameter is model, the following produces the behaviour you expect:

    Expression<Func<Model, string>> expression = model => model.SomeStringProperty;
    Type modelType = expression.Parameters[0].Type;
    MemberExpression expBody = expression.Body as MemberExpression;
    PropertyInfo p = modelType.GetProperty(expBody.Member.Name);
    
    Assert.NotNull(p);
    

    Note that modelType.GetProperty(expBody.Member.Name) is completely unnecessary. It's preferable to extract the member from the MemberExpression itself in order to avoid ambiguity:

    PropertyInfo p = (PropertyInfo)expBody.Member;