最新消息:

【NetCore】使用表达式目录树实现动态组装Where的Linq表达式

博客园精华 William 1浏览 0评论

使用表达式目录树实现动态组装Linq表达式

写在前面

  • 自己开发中遇到的问题,在提供多参数查询列表时,有时候需要写大量的 ifwhere 的Linq表达式
  • 查询参数在特性里配置实体的名字这个参数,尚未使用到。
  • 趁着代码量还不多,做一下记录,给将来自己提供便利的同时,也方便别人。

参考

Gitee仓库

1. 定义 目标实体 类型(例:Student)

public class Student
{
    public string Name { get; set; }
    public string Code { get; set; }
    public int? Age { get; set; }
}

2. 定义 查询参数 类型

// 这里使用与目标实体类型一致的属性
// 后面需要考虑在特性提供字段名,防止耦合太大
public class StudentListQueryParameter
{
    [Where(Type = WhereTypeEnum.Like, Field = nameof(Name))]
    public string Name { get; set; }

    [Where(Type = WhereTypeEnum.Like, Field = nameof(Code))]
    public string Code { get; set; }

    [Where(Type = WhereTypeEnum.Equal, Field = nameof(Age))]
    public int? Age { get; set; }
}

3. 定义 WhereAttribute 特性,用于设置 对比类型字段名

  • 枚举类型
public enum WhereTypeEnum
{
    [UserDescription(Description = "等于")]
    Equal = 0,
    [UserDescription(Description = "大于")]
    Larger = 11,
    [UserDescription(Description = "大于等于")]
    LargerEqual = 12,
    [UserDescription(Description = "小于")]
    Less = 21,
    [UserDescription(Description = "小于等于")]
    LessEqual = 22,
    [UserDescription(Description = "相似")]
    Like = 31,
    [UserDescription(Description = "包含")]
    In = 32,
}

// 不是必要的
public static class UserDescriptionAttributeExtensions
{
    public static string GetUserDescription
        (this EnumType @enum) where EnumType:Enum
    {
        var member = typeof(WhereTypeEnum)
            .GetMember(@enum.ToString())
            .FirstOrDefault();
        var attr = member?.GetCustomAttribute();
        return attr?.Description;
    }
}
  • 查询参数特性

/// 
/// 查询参数特性
/// 
/// 
/// 允许给属性添加,允许多次添加,不可继承
/// 
[AttributeUsage( AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
public class WhereAttribute : Attribute
{
    /// 
    /// 实体属性名
    /// 
    public string Field { get; set; }

    /// 
    /// 对比类型
    /// 
    public WhereTypeEnum Type { get; set; } 
}

IQueryable 拓展方法

 public class BuildWhereOptions
 {
     public StringComparison StringComparison { get; set; } = default;
     public WhereAttribute DefaultAttribute { get; set; } = null;
 }
public static class IQuaryableExtension
{
    /// 
    /// 生成查询条件
    /// 
    /// 查询参数对象
    /// 原有IQueryable
    /// lambda 表达式
    public static Expression> BuildWhere(this IQueryable query, TQueryParams input, Action options = null) where TEntity : class
    {
        // 配置项
        BuildWhereOptions buildWhereOptions = new();
        if (options is not null)
        {
            options(buildWhereOptions);
        }

        var t = Expression.Parameter(typeof(TEntity), "t");
        var trueExpression = Expression.Constant(true);
        var resultExpression = Expression.AndAlso(trueExpression, trueExpression);

        // 遍历入参所有属性
        var queryParamProps = typeof(TQueryParams).GetProperties();
        foreach (var prop in queryParamProps)
        {
            // 根据特性分别处理
            var attr = prop.GetCustomAttribute();

            // 默认不判断,可以通过options参数修改
            if (attr is null)
            {
                attr = buildWhereOptions.DefaultAttribute;
                if (attr is null)
                {
                    continue;
                }
            }

            var entityProperty = Expression.Property(t, prop.Name);
            var v = prop.GetValue(input);
            if (v is null)
            {
                continue;
            }
            var paramValue = Expression.Constant(v, prop.PropertyType);
            switch (attr.Type)
            {
                case WhereTypeEnum.Equal:
                    // t.Name==value;   
                    var p = Expression.Convert(paramValue, entityProperty.Type);
                    var equalExpression = Expression.Equal(entityProperty, p);
                    resultExpression = Expression.AndAlso(resultExpression, equalExpression);

                    break;
                case WhereTypeEnum.Larger:
                    break;
                case WhereTypeEnum.LargerEqual:
                    break;
                case WhereTypeEnum.Less:
                    break;
                case WhereTypeEnum.LessEqual:
                    break;
                case WhereTypeEnum.Like:
                    // t.Name.Contains(value);
                    var containMethod = typeof(string).GetMethod(nameof(string.Contains), new Type[] { typeof(string), typeof(StringComparison) });
                    var stringComparisonValue = Expression.Constant(buildWhereOptions.StringComparison);
                    string s = v as string;
                    if (string.IsNullOrWhiteSpace(s))
                    {
                        continue;
                    }
                    var containMethodExpression = Expression.Call(entityProperty, containMethod, paramValue, stringComparisonValue);
                    resultExpression = Expression.AndAlso(resultExpression, containMethodExpression);
                    break;
                case WhereTypeEnum.In:
                    break;
                default:
                    break;
            }
        }

        return Expression.Lambda>(resultExpression, t);
    }
}

模拟数据调用

static void Main(string[] args)
{
    Console.WriteLine("Hello World!");

    var input = new StudentListQueryParameter()
    {
        // Age = null,
        Code = "A00",
        Name = "张"
    };

    List students = new List {
        new Student{ Code="A001",Name="张三",Age=25},
        new Student{ Code="A002",Name="李四",Age=18},
        new Student{ Code="A003",Name="王五",Age=10},
        new Student{ Code="B001",Name="张四",Age=18},
        new Student{ Code="B002",Name="李五",Age=12},
        new Student{ Code="B003",Name="王六",Age=45},
        new Student{ Code="C001",Name="张五",Age=22},
        new Student{ Code="C001",Name="李六",Age=18},
        new Student{ Code="C001",Name="王七",Age=20},
    };

    var query = students.AsQueryable();
    var result = query.Where(query.BuildWhere(input));

    //var result = query.Where(query.BuildWhere(input, options =>
    //{
    //    options.StringComparison = StringComparison.OrdinalIgnoreCase;
    //    options.DefaultAttribute = null;
    //}));
             
}

不同条件筛选结果展示

Example 1

var input = new StudentListQueryParameter()
{
    // Age = null,
    Code = "A00",
    Name = "张"
};
[
    {"Name":"张三","Code":"A001","Age":25}
]

Example 2

var input = new StudentListQueryParameter()
{
    // Age = null,
    Code = "A00",
    // Name = "张"
};
[
    {"Name":"张三","Code":"A001","Age":25},
    {"Name":"李四","Code":"A002","Age":21},
    {"Name":"王五","Code":"A003","Age":10}
]

Example 3

var input = new StudentListQueryParameter()
{
    // Age = null,
    // Code = "A00",
    Name = "张"
};
[
    {"Name":"张三","Code":"A001","Age":25},
    {"Name":"张四","Code":"B001","Age":31},
    {"Name":"张五","Code":"C001","Age":22}
]

Example 4

var input = new StudentListQueryParameter()
{
    Age = 18,
    // Code = "A00",
    // Name = "张"
};
[
    {"Name":"李四","Code":"A002","Age":18},
    {"Name":"张四","Code":"B001","Age":18},
    {"Name":"李六","Code":"C001","Age":18}
]

文章来源:【NetCore】使用表达式目录树实现动态组装Where的Linq表达式

转载请注明:AspxHtml学习分享网 » 【NetCore】使用表达式目录树实现动态组装Where的Linq表达式

文章评论已关闭!