首页 > 作文

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

更新时间:2023-04-04 07:10:50 阅读: 评论:0

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

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

创建 queryentity 类

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

/// <summary>/// 查询实体/// </summary>public class queryentity{    /// <summary>    /// 字段名称    /// </summary>    public string key { get; t; }    /// <summary>    /// 值    /// </summary>    public string value { get; t; }    /// <summary>    /// 操作方法,对应operatorenum枚举类    /// </summary>    public string operator { get; t; }    /// <summary>    /// 逻辑运算符,只支持and、or    /// </summary>    public string logicaloperator { get; t; }}

创建 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>    lesqual,}

创建 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);            }            el            {                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());        }        el        {            key = expression.property(key, entitykey);        }        expression value = expression.constant(partype(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 partype(queryentity entity)    {            try            {                propertyinfo property;                // 包含'.',说明是子类的字段                if (entity.key.contains('.'))                {                    var tablenameand扶老携幼的意思field = entity.key.split('.');                    property = typeof(t).getproperty(tablenameandfield[0], bindingflags.ignoreca | bindingflags.public | bindingflags.instance);                    property = property.propertytype.getproperty(tablenameandfield[1], bindingflags.ignoreca | bindingflags.public | bindingflags.instance);                }                el                {                    property = typeof(t).getproperty(entity.key, bindingflags.ignoreca | 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.trypar(entityoperator, true, out operatorenum operatorenum))        {            throw new argumentexception("操作方法不存在,请检查operator的值");        }        return operatorenum switch        {                operatorenum.equals => expression.equal(left, expression.convert(value, left.type)),                operatorenum.notequal => expres1000元如何投资理财sion.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.lesqual => expression.lessthanorequal(left, expression.convert(value, left.type)),                _ => expression.equal(left, expression.convert(value, left.type)),        };    }}

使用示例

例如有以下两个实体类,address 是 ur 的子类

public class ur{    public int id { get; t; }    public string name { get; t; } = string.empty;    public int age { get;clear的比较级 t; }    public datetime createtime { get; t; }    public address address { get; t; }}public class address{    public string province { get; t; }    public string city { get; t; }}

单条件查询

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

list<queryentity> list = new list<queryentity>{    new queryentity    {        key = "name",        value = "chen",        operator = "contains"    }};var expression = expressionextension<ur>.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 = expressionex形容词顺序口诀tension<ur>.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<ur>.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动态创建表达式的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。

本文发布于:2023-04-04 07:10:49,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/511727dbc8e5cfd795905066bd98f12c.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:C#表达式树Expression动态创建表达式.doc

本文 PDF 下载地址:C#表达式树Expression动态创建表达式.pdf

标签:表达式   字段   名称   填入
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图