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

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

仅记录,新版本已重构,详细见Gitee代码库

写在前面

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

参考

Nuget 包名 Wosperry.ExpressionExtensions

Gitee仓库:https://gitee.com/wosperry/Wosperry.ExpressionExtensions.git

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<EnumType>
        (this EnumType @enum) where EnumType:Enum
    {
        var member = typeof(WhereTypeEnum)
            .GetMember(@enum.ToString())
            .FirstOrDefault();
        var attr = member?.GetCustomAttribute<UserDescriptionAttribute>();
        return attr?.Description;
    }
}
  • 查询参数特性

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

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

IQueryable<TEnity> 拓展方法

 public class BuildWhereOptions
 {
     public StringComparison StringComparison { get; set; } = default;
     public WhereAttribute DefaultAttribute { get; set; } = null;
 }
public static class IQuaryableExtension
{
    /// <summary>
    /// 生成查询条件
    /// </summary>
    /// <typeparam name="TQueryParams">查询参数对象</typeparam>
    /// <param name="queryable">原有IQueryable</param>
    /// <returns>lambda 表达式</returns>
    public static Expression<Func<TEntity, bool>> BuildWhere<TEntity, TQueryParams>(this IQueryable<TEntity> query, TQueryParams input, Action<BuildWhereOptions> 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<WhereAttribute>();

            // 默认不判断,可以通过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<Func<TEntity, bool>>(resultExpression, t);
    }
}

模拟数据调用

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

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

    List<Student> students = new List<Student> {
        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 result = students.GetList(input);

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

ABP的IRepositry通用仓储等实现了IQueryable的演示


// 之前
public Task<List<Box>> GetListByParamsAsync(BoxQuery input){
    var query = _repository
        .Where(input.f1 is not null, t=>t.F1==input. f1)
        .Where(input.f2 is not null, t=>t.F1==input. f2)
        .Where(input.f3 is not null, t=>t.F1>input. f3)
        .Where(input.f4 is not null, t=>t.F1<input. f4)
        .Where(!string.IsNullOrWhiteSpace(input.f5), t=>t.F1.Contains(input. f5))
        .Where(input.f6 is not null, t=>t.F1==input. f6)
        .Where(input.f7 is not null, t=>t.F1==input. f7)
        .Where(input.f8 is not null, t=>t.F1==input. f8)
        .Where(input.f9 is not null, t=>t.F1==input. f9)
        .Where(input.f10 is not null, t=>t.F1==input.f10)
        .Where(input.f11 is not null, t=>t.F1==input.f11);
    return await AsyncExecuter.ToListAsync(query);
}

// 之后
public Task<List<Box>> GetListByParamsAsync(BoxQuery input){
	// you don't need to care about whether the parameter is null
    var query = _repository.BuildLambda(input);
    return await AsyncExecuter.ToListAsync(query);
}

不同条件筛选结果展示

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}
]
posted @ 2021-10-17 15:51  wosperry  阅读(628)  评论(3编辑  收藏  举报