欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-19 16:30:25
中说到了 expression 的一些概念性东西,其实也是为了这一篇做知识准备。为了实现 efcore 的多条件、连表查询,简化查询代码编写,也就有了这篇文章。在一些管理后台中,对数据进行多条件查询是...

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

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

创建 queryentity 类

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

/// <summary>
/// 查询实体
/// </summary>
public class queryentity
{
    /// <summary>
    /// 字段名称
    /// </summary>
    public string key { get; set; }

    /// <summary>
    /// 值
    /// </summary>
    public string value { get; set; }

    /// <summary>
    /// 操作方法,对应operatorenum枚举类
    /// </summary>
    public string operator { get; set; }

    /// <summary>
    /// 逻辑运算符,只支持and、or
    /// </summary>
    public string logicaloperator { get; set; }
}

创建 operatorenum 类

operatorenum 这是一个操作方法的枚举类,规定了 api 允许的查询方法,比如 equals、contains 等等。

/// <summary>
/// 操作方法枚举
/// </summary>
public enum operatorenum
{
    /// <summary>
    /// 等于
    /// </summary>
    equals,

    /// <summary>
    /// 不等于
    /// </summary>
    notequal,

    /// <summary>
    /// 包含
    /// </summary>
    contains,

    /// <summary>
    /// 由什么开始
    /// </summary>
    startswith,

    /// <summary>
    /// 由什么结束
    /// </summary>
    endswith,

    /// <summary>
    /// 大于
    /// </summary>
    greater,

    /// <summary>
    /// 大于等于
    /// </summary>
    greaterequal,

    /// <summary>
    /// 小于
    /// </summary>
    less,

    /// <summary>
    /// 小于等于
    /// </summary>
    lessequal,
}

创建 expressionextension 类

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

/// <summary>
/// 表达式扩展
/// </summary>
/// <typeparam name="t">泛型</typeparam>
public static class expressionextension<t> where t : class, new()
{
    /// <summary>
    /// 表达式动态拼接
    /// </summary>
    public static expression<func<t, bool>> expressionsplice(list<queryentity> 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<expression>());
            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<func<t, bool>>(binary, expression.parameters);
        }
        return expression_first;
    }

    /// <summary>
    /// 创建 expression<tdelegate>
    /// </summary>
    private static expression<func<t, bool>> 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<func<t, bool>>(body, param);
        return lambda;
    }

    /// <summary>
    /// 属性类型转换
    /// </summary>
    /// <param name="entity">查询实体</param>
    /// <returns></returns>
    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("字段类型转换失败:字段名错误或值类型不正确");
            }
    }

    /// <summary>
    /// 创建 expression
    /// </summary>
    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<queryentity> list = new list<queryentity>
{
    new queryentity
    {
        key = "name",
        value = "chen",
        operator = "contains"
    }
};
var expression = expressionextension<user>.expressionsplice(list);
// expression = param_0 => param_0.name.contains("chen")

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

list<queryentity> list = new list<queryentity>
{
    new queryentity
    {
        key = "age",
        value = "18",
        operator = "greaterequal"
    }
};
var expression = expressionextension<user>.expressionsplice(list);
// expression = param_0 => param_0.name.greaterthanorequal(18)

多条件查询

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

list<queryentity> list = new list<queryentity>
{
    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<user>.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<queryentity> list = new list<queryentity>
{
    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<bookingrecord>.expressionsplice(list);
// expression = {param_0 => ((param_0.address.province == convert("广东省", string)) and invoke(param_1 => param_1.name.contains("chen"), param_0))}

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