2

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

6
  • Have you tried a reflection based factory? Commented Nov 23, 2016 at 12:20
  • 2
    Have a look at Expression trees. Commented Nov 23, 2016 at 12:20
  • 1
    Is an Expression<Func<object>> what you want? The Entity is coming from your application (not an input to the expression) and its Id property is a long not an object. Would an Expression<Func<Entity, long>> be more useful? For example: Expression<Func<Entity, long>> target = a => a.Id; Commented Nov 23, 2016 at 12:23
  • I do want use Expression trees but I only start working with them Commented Nov 23, 2016 at 12:23
  • why not simply use nameof(Entity.Id)? Commented Jan 9, 2017 at 19:05

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, but I really need Expression<Func<object>> because I want to pass it to another method which can accept only Expression<Func<object>>(it's WithAlias method from NHibernate)
Sorry, but I need not Expression<Func<Entity, object>> but Expression<Func<object>>. Just like this: () => alias.Id
It this is the desired method, you could replace this Entity entity with this T source to make this method available on all kind of objects.
Thanks a lot. That's exactly what I need!
It's better to var expression = Expression.Lambda<Func<object>>(convertExpr); than to cast later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.