Reputation: 1735
I am trying to translate a LinqExpression into a sql statement. For example, on my Repository base class I have a method Find that accepts a LinqExpression as its argument. Within the Find method, I am calling a method that performs the following action:
var equality = expression as BinaryExpression;
return equality.Left.Translate() + " = " +
equality.Right.Translate();
How can I get the value of the variable on the right side and not just the variable name, currently I am only getting the variable name. ex. Find(x => x.ID = variable); if variable is currently set to 7 I need a way to get the value 7 and not the name variable. What would be the correct way to get to the value stored in the variable?
Upvotes: 3
Views: 129
Reputation: 982
Try casting into MemberExpression or ConstantExpression respectively:
var memberExpression = (MemberExpression) expression.Left;
var constantExpression = (ConstantExpression) expression.Right;
Oh, missed it was a variable. Then the right operand should be of type ParameterException. However, to get its value you may use
Func<object> getValue = expression.Compile();
var value = getValue();
Note that this may be slow.
Upvotes: 0
Reputation: 244948
Have a look at Matt Warren's article LINQ: Building an IQueryable Provider - Part III. It contains code for Evaluator
class which will inline all values that can be inlined. In your case, it will replace variable
with a ConstantExpression
that contains the value 7.
The rest of the articles in the series might be of interest to you too.
Upvotes: 1