How to create Expression<Func<object>> from property name
Asked Answered
G

1

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

Gatecrasher answered 23/11, 2016 at 12:18 Comment(6)
Have you tried a reflection based factory?Rooftree
Have a look at Expression trees.Poulos
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;Borodin
I do want use Expression trees but I only start working with themGatecrasher
why not simply use nameof(Entity.Id)?Vega
Possible duplicate of Retrieving Property name from lambda expressionReardon
P
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.

Paresis answered 23/11, 2016 at 12:35 Comment(5)
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)Gatecrasher
Sorry, but I need not Expression<Func<Entity, object>> but Expression<Func<object>>. Just like this: () => alias.IdGatecrasher
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.Cotswolds
Thanks a lot. That's exactly what I need!Gatecrasher
It's better to var expression = Expression.Lambda<Func<object>>(convertExpr); than to cast later.Kerr

© 2022 - 2024 — McMap. All rights reserved.