Prajwal
Prajwal

Reputation: 4000

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.

Upvotes: 0

Views: 1024

Answers (2)

Kirill Shlenskiy
Kirill Shlenskiy

Reputation: 9587

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;

Upvotes: 0

Ben
Ben

Reputation: 763

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

MemberExpression expbody = expression.Body as MemberExpression;
Type modelType = expbody.Expression.Type;

Upvotes: 1

Related Questions