using System.Linq.Expressions;
var visitor = new SqlExpressionVisitor();
string sql = visitor.TranslateToSql<Employee>(e => e.Name == "Spencer" && e.Age > 30);
public string Name { get; set; }
public int Age { get; set; }
public class SqlExpressionVisitor : ExpressionVisitor
private StringBuilder sb;
private bool isWhereClauseStarted = false;
public SqlExpressionVisitor()
sb = new StringBuilder();
public string TranslateToSql<T>(Expression<Func<T, bool>> expression)
sb.Append("SELECT * FROM ");
sb.Append(typeof(T).Name);
isWhereClauseStarted = true;
protected override Expression VisitBinary(BinaryExpression node)
if (!isWhereClauseStarted)
isWhereClauseStarted = true;
case ExpressionType.AndAlso:
case ExpressionType.Equal:
case ExpressionType.GreaterThan:
throw new NotSupportedException($"Operation '{node.NodeType}' is not supported");
protected override Expression VisitConstant(ConstantExpression node)
if (node.Value is string)
sb.Append($"'{node.Value}'");
protected override Expression VisitMember(MemberExpression node)
if (node.Expression != null && node.Expression.NodeType == ExpressionType.Parameter)
sb.Append(node.Member.Name);
throw new NotSupportedException($"Unsupported expression part '{node}'");