Search code examples
c#linqlinq-expressions

How to create Expression<Func<object>> from property name


I want to create an expression like this:

public class Entity
{        
    public virtual long Id { get; set; }
}

Entity alias = null;
Expression<Func<object>> target = () => alias.Id;//have to be created from "Id"

My question is how to create Expression<Func<object>> target programaticaly having string with property name("Id" in this example).


Solution

  • 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.