C#表达式树Expression动态创建表达式

上一篇中说到了 Expression 的一些概念性东西,其实也是为了这一篇做知识准备。为了实现 EFCore 的多条件、连表查询,简化查询代码编写,也就有了这篇文章。

在一些管理后台中,对数据进行多条件查询是一件很普遍的事情,比如在用户列表需要实现可以对 "用户名"、"手机号"、"账户是否冻结" 等等一系列的条件查询,常见的处理方式就是通过一系列 if...else... 来对条件进行拼接。这会导致查询接口实现起来堆叠了一堆看起来有用但实际很繁琐的代码。所以根据前后端请求报文协商,我们就可以按照一定的格式来动态创建表达式树。

创建 QueryEntity 类

QueryEntity 是前端向 API 传递的参数列表,通过这个类,服务端可以知道前端需要查询哪个字段,使用什么方法(Equals、Contains)过滤。

/// 
/// 查询实体
/// 
public class QueryEntity
{
    /// 
    /// 字段名称
    /// 
    public string Key { get; set; }

    /// 
    /// 值
    /// 
    public string Value { get; set; }

    /// 
    /// 操作方法,对应OperatorEnum枚举类
    /// 
    public string Operator { get; set; }

    /// 
    /// 逻辑运算符,只支持AND、OR
    /// 
    public string LogicalOperator { get; set; }
}

创建 OperatorEnum 类

OperatorEnum 这是一个操作方法的枚举类,规定了 API 允许的查询方法,比如 Equals、Contains 等等。

/// 
/// 操作方法枚举
/// 
public enum OperatorEnum
{
    /// 
    /// 等于
    /// 
    Equals,

    /// 
    /// 不等于
    /// 
    NotEqual,

    /// 
    /// 包含
    /// 
    Contains,

    /// 
    /// 由什么开始
    /// 
    StartsWith,

    /// 
    /// 由什么结束
    /// 
    EndsWith,

    /// 
    /// 大于
    /// 
    Greater,

    /// 
    /// 大于等于
    /// 
    GreaterEqual,

    /// 
    /// 小于
    /// 
    Less,

    /// 
    /// 小于等于
    /// 
    LessEqual,
}

创建 ExpressionExtension 类

ExpressionExtension 类实现了表达式树的动态创建,将前端传入的多条件查询转换成表达式,用于 EFCore 的查询。

/// 
/// 表达式扩展
/// 
/// 泛型
public static class ExpressionExtension where T : class, new()
{
    /// 
    /// 表达式动态拼接
    /// 
    public static Expression> ExpressionSplice(List entities)
    {
        if (entities.Count < 1)
        {
            return ex => true;
        }
        var expression_first = CreateExpressionDelegate(entities[0]);
        foreach (var entity in entities.Skip(1))
        {
            var expression = CreateExpressionDelegate(entity);
            InvocationExpression invocation = Expression.Invoke(expression_first, expression.Parameters.Cast());
            BinaryExpression binary;
            // 逻辑运算符判断
            if (entity.LogicalOperator.ToUpper().Equals("OR"))
            {
                binary = Expression.Or(expression.Body, invocation);
            }
            else
            {
                binary = Expression.And(expression.Body, invocation);
            }
            expression_first = Expression.Lambda>(binary, expression.Parameters);
        }
        return expression_first;
    }

    /// 
    /// 创建 Expression
    /// 
    private static Expression> CreateExpressionDelegate(QueryEntity entity)
    {
        ParameterExpression param = Expression.Parameter(typeof(T));

        Expression key = param;
        var entityKey = entity.Key.Trim();
        // 包含'.',说明是父表的字段
        if (entityKey.Contains('.'))
        {
            var tableNameAndField = entityKey.Split('.');
            key = Expression.Property(key, tableNameAndField[0].ToString());
            key = Expression.Property(key, tableNameAndField[1].ToString());
        }
        else
        {
            key = Expression.Property(key, entityKey);
        }

        Expression value = Expression.Constant(ParseType(entity));
        Expression body = CreateExpression(key, value, entity.Operator);
        var lambda = Expression.Lambda>(body, param);
        return lambda;
    }

    /// 
    /// 属性类型转换
    /// 
    /// 查询实体
    /// 
    private static object ParseType(QueryEntity entity)
    {
            try
            {
                PropertyInfo property;
                // 包含'.',说明是子类的字段
                if (entity.Key.Contains('.'))
                {
                    var tableNameAndField = entity.Key.Split('.');

                    property = typeof(T).GetProperty(tableNameAndField[0], BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                    property = property.PropertyType.GetProperty(tableNameAndField[1], BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                }
                else
                {
                    property = typeof(T).GetProperty(entity.Key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                }

                return Convert.ChangeType(entity.Value, property.PropertyType);
            }
            catch (Exception)
            {
                throw new ArgumentException("字段类型转换失败:字段名错误或值类型不正确");
            }
    }

    /// 
    /// 创建 Expression
    /// 
    private static Expression CreateExpression(Expression left, Expression value, string entityOperator)
    {
        if (!Enum.TryParse(entityOperator, true, out OperatorEnum operatorEnum))
        {
            throw new ArgumentException("操作方法不存在,请检查operator的值");
        }

        return operatorEnum switch
        {
                OperatorEnum.Equals => Expression.Equal(left, Expression.Convert(value, left.Type)),
                OperatorEnum.NotEqual => Expression.NotEqual(left, Expression.Convert(value, left.Type)),
                OperatorEnum.Contains => Expression.Call(left, typeof(string).GetMethod("Contains", new Type[] { typeof(string) }), value),
                OperatorEnum.StartsWith => Expression.Call(left, typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }), value),
                OperatorEnum.EndsWith => Expression.Call(left, typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) }), value),
                OperatorEnum.Greater => Expression.GreaterThan(left, Expression.Convert(value, left.Type)),
                OperatorEnum.GreaterEqual => Expression.GreaterThanOrEqual(left, Expression.Convert(value, left.Type)),
                OperatorEnum.Less => Expression.LessThan(left, Expression.Convert(value, left.Type)),
                OperatorEnum.LessEqual => Expression.LessThanOrEqual(left, Expression.Convert(value, left.Type)),
                _ => Expression.Equal(left, Expression.Convert(value, left.Type)),
        };
    }
}

使用示例

例如有以下两个实体类,Address 是 User 的子类

public class User
{
    public int Id { get; set; }

    public string Name { get; set; } = string.Empty;

    public int Age { get; set; }

    public DateTime CreateTime { get; set; }

    public Address Address { get; set; }

}

public class Address
{
    public string Province { get; set; }

    public string City { get; set; }
}

单条件查询

查询用户表中名称(name) 包含 "chen" :

List list = new List
{
    new QueryEntity
    {
        Key = "name",
        Value = "chen",
        Operator = "Contains"
    }
};
var expression = ExpressionExtension.ExpressionSplice(list);
// expression = Param_0 => Param_0.Name.Contains("chen")

查询用户表中年龄(age) 大于等于 18:

List list = new List
{
    new QueryEntity
    {
        Key = "age",
        Value = "18",
        Operator = "GreaterEqual"
    }
};
var expression = ExpressionExtension.ExpressionSplice(list);
// expression = Param_0 => Param_0.Name.GreaterThanOrEqual(18)

多条件查询

查询用户表中名称(name) 包含 "chen" 并且年龄(age) 大于等于 18:

List list = new List
{
    new QueryEntity
    {
        Key = "name",
        Value = "chen",
        Operator = "Contains"
    },
    new QueryEntity
    {
        Key = "age",
        Value = "18",
        Operator = "GreaterEqual",
        // 注意:这里得填入 "AND",代表两个条件是并且的关系,如果需要查询名称包含 "chen" 或者 年龄大于等于18,则填入 "OR"
        "logicalOperator": "AND"
    }
};
var expression = ExpressionExtension.ExpressionSplice(list);
// expression = Param_0 => ((Param_0.Status >= Convert(1, Int32)) And Invoke(Param_1 => Param_1.OpenId.Contains("9JJdFTVt6oimCgdbW61sk"), Param_0))

多表查询

查询用户表中名称(name) 包含 "chen" 并且 地址(address)在广东省:

List list = new List
{
    new QueryEntity
    {
        Key = "name",
        Value = "chen",
        Operator = "Contains"
    },
    new QueryEntity
    {
        Key = "address.Province",
        Value = "广东省",
        Operator = "Equals",
        // 注意:这里得填入 "AND",代表两个条件是并且的关系,如果需要查询名称包含 "chen" 或者 年龄大于等于18,则填入 "OR"
        "logicalOperator": "AND"
    }
};

var expression = ExpressionExtension.ExpressionSplice(list);
// expression = {Param_0 => ((Param_0.Address.Province == Convert("广东省", String)) And Invoke(Param_1 => Param_1.Name.Contains("chen"), Param_0))}

到此这篇关于C#表达式树Expression动态创建表达式的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(C#表达式树Expression动态创建表达式)