Create an expression from PropertyInfo

I use the API that expects Expression<Func<T, object>> , and uses it to create mappings between different objects:

 Map(x => x.Id).To("Id__c"); // The expression is "x => x.Id" 

How to create the necessary expression from PropertyInfo ? The idea was as follows:

 var properties = typeof(T).GetProperties(); foreach (var propInfo in properties) { var exp = // How to create expression "x => x.Id" ??? Map(exp).To(name); } 
+5
source share
1 answer

You just need Expression.Property , and then wrap it in lambda. One tricky bit is that you also need to convert the result to object :

 var parameter = Expression.Parameter(x); var property = Expression.Property(parameter, propInfo); var conversion = Expression.Convert(property, typeof(object)); var lambda = Expression.Lambda<Func<T, object>>(conversion, parameter); Map(lambda).To(name); 
+7
source

Source: https://habr.com/ru/post/1233398/


All Articles