How to convert an expression tree to a partial SQL query?

后端 未结 9 1550
轮回少年
轮回少年 2020-11-29 16:26

When EF or LINQ to SQL runs a query, it:

  1. Builds an expression tree from the code,
  2. Converts the expression tree into an SQL query,
  3. Executes th
9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 17:06

    It isn't complete, but here are some thoughts for you to groove on if you come by this later:

        private string CreateWhereClause(Expression> predicate)
        {
            StringBuilder p = new StringBuilder(predicate.Body.ToString());
            var pName = predicate.Parameters.First();
            p.Replace(pName.Name + ".", "");
            p.Replace("==", "=");
            p.Replace("AndAlso", "and");
            p.Replace("OrElse", "or");
            p.Replace("\"", "\'");
            return p.ToString();
        }
    
        private string AddWhereToSelectCommand(Expression> predicate, int maxCount = 0)
        {           
            string command = string.Format("{0} where {1}", CreateSelectCommand(maxCount), CreateWhereClause(predicate));
            return command;
        }
    
        private string CreateSelectCommand(int maxCount = 0)
        {
            string selectMax = maxCount > 0 ? "TOP " + maxCount.ToString() + " * " : "*";
            string command = string.Format("Select {0} from {1}", selectMax, _tableName);
            return command;
        }
    

提交回复
热议问题