mardi 24 septembre 2019

C# Is there a way to resolve lamba expression`s delegate type in code

My goal is to support sorting in the application and expose it via REST API that would accept the parameter as a string.

Current implementation is along the lines of this:

GetUsers (Expression<Func<User, int>> sortExpression) {
 // Retrieve users ... 
 return users.orderBy(sortExpression);
}

Usage example:
var users = GetUsers(u => u.Id);

the Expression<Func<User, int>> sortExpression is widely used in our repository and changing it would be difficult.

What I'd like to do is to be able to swap the u => u.Id with something that is generated during run-time.

Something that I have so far is:

// sortBy is retrieved from the calling method.
var type = typeof(User).GetProperties().FirstOrDefault(x => x.Name == sortBy).GetType();

var sortExpression = Expression.Property(Expression.Parameter(typeof(User)), sortBy);

var parameter = Expression.Parameter(typeof(User));

var expressionBody = Expression.Lambda(typeof(Func<User, int>), sortExpression, parameter);

var users = GetUsers(expressionBody)

I can see at run-time that this does create an expression that fits my needs, but the error is Argument 5: cannot convert from 'LambdaExpression' to 'Expression<System.Func<User, int>>' even though the body of the expression is supposed to be set by typeof(Func<User, int>)





Aucun commentaire:

Enregistrer un commentaire