I want to loop through my model properties using reflection, and then pass them into a method expecting my property as en expression.
For example, given this model:
public class UserModel
{
public string Name { get; set; }
}
And this validator class:
public class UserValidator : ValidatorBase<UserModel>
{
public UserValidator()
{
this.RuleFor(m => m.Username);
}
}
And my ValidatorBase class:
public class ValidatorBase<T>
{
public ValidatorBase()
{
foreach (PropertyInfo property in
this.GetType().BaseType
.GetGenericArguments()[0]
.GetProperties(BindingFlags.Public | BindingFlags.Insance))
{
this.RuleFor(m => property); //This line is incorrect!!
}
}
public void RuleFor<TProperty>(Expression<Func<T, TProperty>> expression)
{
//Do some stuff here
}
}
The issue is with the ValidatorBase() constructor -- given that I have the PropertyInfo for the property I need, what should I pass into as the expression parameter in the RuleFor method, such that it works just like the line in UserValidator() constructor?
Or, should I be using something else besides PropertyInfo to get this to work?