Home > front end >  Translate lambda into sql query
Translate lambda into sql query

Time:12-17

I want to convert a simple LambdaExpression into sql query. I am trying to do this by using ExpressionTrees like this:

Expression<Func<Person, bool>> exp = (person) => person.ID == 5;

when where is a constant right node in the expression, I can retrieve data and I am getting dictionary like this:

new Dictionary<string, object>() { { "ID", 5 } };

but when there is a property access in the right node, my code fails, because MemberExpression can not be converted into ConstantExpression. For example, I can not get person ID value from this lambda expression:

Person person = new Person()
{
    ID = 1,
    Name = "Test",
    Lastname = "Test"
};

Expression<Func<Person, bool>> exp = (p) => p.ID == person.ID;

Question: How to retrieve body data from LambdaExpression, when there is property access in right node.

CodePudding user response:

If you want to write down the expression directly I do not think you can use person like this. This is not "selfcontained" and comes from outside. If you wish to write down the expression you need to make person accessable within the expression. From what I understand you are looking for something like this:

public static Expression<Func<Person, bool>> GetPredicate(
    Person person)
{
    var parameter = Expression.Parameter(typeof(Person), "o");
    var propertyInfo = typeof(Person).GetProperty(nameof(Person.Name));
    var expression = Expression.Equal(
        Expression.Constant(propertyInfo.GetValue(person)),
        Expression.Property(parameter, propertyInfo));
    return Expression.Lambda<Func<Person, bool>>(expression, parameter);
}
  • Related