1. 程式人生 > >【手擼一個ORM】第四步、Expression(表達式目錄樹)擴展

【手擼一個ORM】第四步、Expression(表達式目錄樹)擴展

clas access stat ber expr req exc nodetype 支持

一、表達式目錄樹解析時需要的擴展方法

  1. 表達式操作符轉SQL操作符
  2. 獲取MemberExpression的根類型,後面需要根據該類型進行不同的操作
  3. 獲取表達式目錄路的值
using System;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace MyOrm.Expressions
{
    public static class ExpressionExtensions
    {
        public static string ToSqlOperator(this
ExpressionType type) { switch (type) { case (ExpressionType.AndAlso): case (ExpressionType.And): return " AND "; case (ExpressionType.OrElse): case (ExpressionType.Or):
return " OR "; case (ExpressionType.Not): return " NOT "; case (ExpressionType.NotEqual): return "<>"; case ExpressionType.GreaterThan: return ">"; case ExpressionType.GreaterThanOrEqual:
return ">="; case ExpressionType.LessThan: return "<"; case ExpressionType.LessThanOrEqual: return "<="; case (ExpressionType.Equal): return "="; default: throw new Exception("不支持該方法"); } } public static ExpressionType GetRootType(this MemberExpression expression, out Stack<string> stack) { var memberExpr = expression; var parentExpr = expression.Expression; stack = new Stack<string>(); stack.Push(expression.Member.Name); while (parentExpr != null && parentExpr.NodeType == ExpressionType.MemberAccess) { memberExpr = (MemberExpression)parentExpr; parentExpr = ((MemberExpression)parentExpr).Expression; stack.Push(memberExpr.Member.Name); } return parentExpr?.NodeType ?? memberExpr.NodeType; } public static object GetValue(this Expression expression) { if (expression.NodeType == ExpressionType.Constant) { return ((ConstantExpression)expression).Value; } else { var cast = Expression.Convert(expression, typeof(object)); return Expression.Lambda<Func<object>>(cast).Compile().Invoke(); } } } }

【手擼一個ORM】第四步、Expression(表達式目錄樹)擴展