0

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.

Prajwal
  • 3,930
  • 5
  • 24
  • 50
  • 1
    Please read [ask]. How do you call this ("passing model" is unclear)? How is this "not working"? What have you tried? See [Get property type by MemberExpression](https://stackoverflow.com/questions/10224119/get-property-type-by-memberexpression) and [.NET reflection - Get Declaring class type from instance property](https://stackoverflow.com/questions/5017744/net-reflection-get-declaring-class-type-from-instance-property). – CodeCaster Jul 26 '17 at 11:32

2 Answers2

1

If you want to get the type of the model, just do this:

MemberExpression expbody = expression.Body as MemberExpression;
Type modelType = expbody.Expression.Type;
Ben
  • 763
  • 1
  • 5
  • 14
0

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;
Kirill Shlenskiy
  • 9,367
  • 27
  • 39