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

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

写在前面

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

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>();

            // 默认判断是否相等
            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=21},
        new Student{ Code="A003",Name="王五",Age=10},
        new Student{ Code="B001",Name="张四",Age=31},
        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}
]

参考

上一篇:.netcore应用容器化部署


下一篇:在.NetCore(C#)中使用ODP.NET Core+Dapper操作Oracle数据库