您好,登錄后才能下訂單哦!
本篇內容介紹了“怎么用C#表達式樹Expression動態創建表達式”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
在一些管理后臺中,對數據進行多條件查詢是一件很普遍的事情,比如在用戶列表需要實現可以對 "用戶名"、"手機號"、"賬戶是否凍結" 等等一系列的條件查詢,常見的處理方式就是通過一系列 if...else... 來對條件進行拼接。這會導致查詢接口實現起來堆疊了一堆看起來有用但實際很繁瑣的代碼。所以根據前后端請求報文協商,我們就可以按照一定的格式來動態創建表達式樹。
QueryEntity 是前端向 API 傳遞的參數列表,通過這個類,服務端可以知道前端需要查詢哪個字段,使用什么方法(Equals、Contains)過濾。
/// <summary> /// 查詢實體 /// </summary> public class QueryEntity { /// <summary> /// 字段名稱 /// </summary> public string Key { get; set; } /// <summary> /// 值 /// </summary> public string Value { get; set; } /// <summary> /// 操作方法,對應OperatorEnum枚舉類 /// </summary> public string Operator { get; set; } /// <summary> /// 邏輯運算符,只支持AND、OR /// </summary> public string LogicalOperator { get; set; } }
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> LessEqual, }
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); } else { 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()); } else { key = Expression.Property(key, entityKey); } Expression value = Expression.Constant(ParseType(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 ParseType(QueryEntity entity) { try { PropertyInfo property; // 包含'.',說明是子類的字段 if (entity.Key.Contains('.')) { var tableNameAndField = entity.Key.Split('.'); property = typeof(T).GetProperty(tableNameAndField[0], BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); property = property.PropertyType.GetProperty(tableNameAndField[1], BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); } else { property = typeof(T).GetProperty(entity.Key, BindingFlags.IgnoreCase | 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.TryParse(entityOperator, true, out OperatorEnum operatorEnum)) { throw new ArgumentException("操作方法不存在,請檢查operator的值"); } return operatorEnum switch { OperatorEnum.Equals => Expression.Equal(left, Expression.Convert(value, left.Type)), OperatorEnum.NotEqual => Expression.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.LessEqual => Expression.LessThanOrEqual(left, Expression.Convert(value, left.Type)), _ => Expression.Equal(left, Expression.Convert(value, left.Type)), }; } }
例如有以下兩個實體類,Address 是 User 的子類
public class User { public int Id { get; set; } public string Name { get; set; } = string.Empty; public int Age { get; set; } public DateTime CreateTime { get; set; } public Address Address { get; set; } } public class Address { public string Province { get; set; } public string City { get; set; } }
查詢用戶表中名稱(name) 包含 "chen" :
List<QueryEntity> list = new List<QueryEntity> { new QueryEntity { Key = "name", Value = "chen", Operator = "Contains" } }; var expression = ExpressionExtension<User>.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 = ExpressionExtension<User>.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<User>.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動態創建表達式”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。