Created
October 12, 2012 23:25
-
-
Save gosukiwi/3882238 to your computer and use it in GitHub Desktop.
Parse an Expression into a SQL Where
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private string parsePredicateExpression(Expression body) | |
{ | |
BinaryExpression binary = (BinaryExpression)body; // cast | |
string separator = body.NodeType == ExpressionType.OrElse ? " OR " : " AND "; | |
if (body.NodeType == ExpressionType.AndAlso || body.NodeType == ExpressionType.OrElse) | |
{ // If we are working with several ANDs or ORs | |
return "(" + parsePredicateExpression(binary.Left) + separator + parsePredicateExpression(binary.Right) + ")"; | |
} | |
else | |
{ | |
MemberExpression member = (MemberExpression)binary.Left; | |
string output = member.Member.Name; | |
switch (body.NodeType) | |
{ // Given the node type of the expression, we set the correct string, normally it's equal (x.Id == 1) | |
default: | |
case ExpressionType.Equal: | |
output += " = "; | |
break; | |
case ExpressionType.NotEqual: | |
output += " <> "; | |
break; | |
case ExpressionType.GreaterThan: | |
output += " > "; | |
break; | |
case ExpressionType.GreaterThanOrEqual: | |
output += " >= "; | |
break; | |
case ExpressionType.LessThan: | |
output += " < "; | |
break; | |
case ExpressionType.LessThanOrEqual: | |
output += " <= "; | |
break; | |
} | |
object val = null; | |
if (binary.Right.NodeType == ExpressionType.MemberAccess) | |
{ | |
var exp = (MemberExpression)binary.Right; | |
val = GetValue(exp); | |
} | |
else | |
{ | |
ConstantExpression constant = (ConstantExpression)binary.Right; | |
val = constant.Value; | |
} | |
if (val is int) { output += val; } | |
else { output += "\"" + val + "\""; } | |
return output; | |
} | |
} | |
private object GetValue(MemberExpression member) | |
{ | |
var objectMember = Expression.Convert(member, typeof(object)); | |
var getterLambda = Expression.Lambda>(objectMember); | |
var getter = getterLambda.Compile(); | |
return getter(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment