I have a method that uses an expression to define its output:
public async Task<TOut>
GetCustomerAsync<TOut>(
int customerId,
Expression<Func<Models.Customer, TOut>> map)
{
return await _customerService.GetMappedSingleAsync(
map,
customer => customer.Id == customerId;
}
I then have a number of different static expression methods that I can pass into this method, for example:
public static class CustomerExpressions
{
public static Expression<Func<Models.Customer, CustomerItemDto>>
CustomerItemDtoExpression()
{
return customer => new CustomerItemDto
{
CustomerId = customer.Id,
CustomerName = customer.Name
};
}
}
The main method can then be called like this:
var customer = await _customerUiService.GetCustomerAsync(
id, CustomerExpressions.CustomerItemDtoExpression());
I would now like to use reflection to create the expression tree from the designated expression method, so I could select the required expression by name. Something like this:
var dtoName = "CustomerItemDto";
var methodName = dtoName + "Expression";
var classType = typeof(CustomerExpressions);
var method = classType.GetMethod(methodName);
var expressionTree = /* Create an expression tree from the method */
var customer = await _customerUiService
.GetCustomerAsync(id, expressionTree);
In other words, how can I compile the expression tree from my method's MethodInfo?
Any help would be much appreciated.
Update
So I have now got a little further with the code thanks to the comments
var dtoName = "CustomerItemDto";
var methodName = dtoName + "Expression";
var classType = typeof(CustomerExpressions);
var method = classType.GetMethod(methodName);
var expressionTree = method.Invoke(null, null);
// The problem now is that expressionTree is returned as an object,
// when, in this example, it needs to be of type
// Expression<Func<Models.Customer, TOut>>
var customer = await _customerUiService
.GetCustomerAsync(id, expressionTree);
The problem now is that expressionTree
is returned as an object
, when it needs to be of type Expression<Func<Models.Customer, TOut>>
- in this particular case the return type of the method Expression<Func<Models.Customer, CustomerItemDto>>