OK, I hope, i have finally understood, what do you need :)
I suggest to create such extension method:
public static class EntityExtensions
{
public static Expression<Func<object>> ToExpression(this Entity entity, string property)
{
var constant = Expression.Constant(entity);
var memberExpression = Expression.Property(constant, property);
Expression convertExpr = Expression.Convert(memberExpression, typeof(object));
var expression = Expression.Lambda(convertExpr);
return (Expression<Func<object>>)expression;
}
}
and than call it this way:
var entity = new Entity { Id = 4711 };
var expression = entity.ToExpression("Id");
var result = expression.Compile().DynamicInvoke();
You have to give entity as a parameter.
People, who downvote accepted answer, could explain, what the probem it.
Expression<Func<object>>
what you want? TheEntity
is coming from your application (not an input to the expression) and itsId
property is along
not anobject
. Would anExpression<Func<Entity, long>>
be more useful? For example:Expression<Func<Entity, long>> target = a => a.Id;
– Borodinnameof(Entity.Id)
? – Vega