Creating an expression returning an object

I have this method:

public R TranslateExpression<R>(Expression exp)
       where R : DbRequest
{
           //...
}

In another class, I have the following method:

public void Persist(E entity)
{
     Expression expr = Expression.Return(entity); //Does not compile, but I'm looking for something like this

     PersistRequest request = TranslateExpression<PersistRequest>(expr);
}

How to create Expressionone that just returns an instance?

Something like this: () => { return entity; }.

+4
source share
1 answer

You can create Expression<Func<E>>and then use a lambda expression to return your entity after calling the expression.

public void Persist<E>(E entity)
{
    Expression<Func<E>> expr = () => entity;    
    PersistRequest request = TranslateExpression<PersistRequest>(expr);
}

public R TranslateExpression<R>(Expression exp)
       where R : DbRequest
{
}

However, your method is TranslateExpressionnot particularly useful at the moment, as you have lost the power of your expression. If you are not doing something special inside TranslateExpression, it might be better suited for something like the following signature:

public R TranslateExpression<R, E>(Expression<Func<E>> exp)
       where R : DbRequest
{
}
+2
source

All Articles