【NetCore】使用表示式目錄樹實現動態組裝Linq表示式
阿新 • • 發佈:2021-10-17
使用表示式目錄樹實現動態組裝Linq表示式
寫在前面
- 自己開發中遇到的問題,在提供多引數查詢列表時,有時候需要寫大量的
if
和where
的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}
]