I am wanting to create a MemberExpression knowing only the field name; eg:
public static Expression<Func<TModel, T>> GenerateMemberExpression<TModel, T>(string fieldName)
{
PropertyInfo fieldPropertyInfo;
fieldPropertyInfo = typeof(TModel).GetProperty(fieldName);
var entityParam = Expression.Parameter(typeof(TModel), "e"); // {e}
var columnExpr = Expression.MakeMemberAccess(entityParam, fieldPropertyInfo); // {e.fieldName}
var lambda = Expression.Lambda(columnExpr, entityParam) as Expression<Func<TModel, T>>; // {e => e.column}
return lambda;
}
The problem with the above is that the field type must be strongly typed. Passing "object" in as the field type doesn't work. Is there any way to generate this? Even Dynamic LINQ doesn't appear to work.
Try manually converting the field value in case of passing an "object". For example:
Hope this will help you.
There are a number of issues with your code:
fieldName
, but you are getting a property out with it.Expression.Lambda
method to generate the expression, which may choose an inappropriate delegate-type if the type-argumentT
passed to the method is not the same as the property-type. In this case, theas
cast from the expression to the method's return-type will fail and evaluate tonull
. Solution: Use the genericLambda
method with the appropriate type-arguments. No casting required.T
, but not when more complicated conversions such as boxing / lifting are required. Solution: Use theExpression.Convert
method where necessary.Here's an update to your sample that addresses these issues:
This will make all of the following calls succeed: