1. 程式人生 > >Lambda 表示式動態拼接.

Lambda 表示式動態拼接.

背景:

專案使用EF 查詢時需要手動判斷條件寫.覺得太麻煩就Google 如何動態生成Linq.最後找到了 System.Linq.Dynamic.Core. 這個東西.

Scott Guthrie 老爺子也有參與.

在Nuget 中直接查詢 安裝 .

引用  System.Linq.Dynamic.Core; System.Linq.Expressions; 這兩個名稱空間 並在合適的地方編寫如下幫助類.

public class LinqExpressionBuilder<TEntity>
    {
        /// <summary>
/// 生成查詢表示式 /// </summary> /// <param name="dto"></param> /// <param name="excludeFields"></param> /// <returns></returns> public Expression<Func<TEntity, bool>> Build(object dto, Dictionary<string, object> excludeFields = null
) { var parameters = GenerateParametersDictionary(dto, excludeFields); StringBuilder sb = new StringBuilder(); var fieldNames = parameters.Keys.ToList(); // 動態拼接 for (int i = 0; i < fieldNames.Count; i++) {
//自定義查詢拼接 if (fieldNames[i] == "BeginData") { sb.Append("CreateTime").Append($" > @{i}").Append(" && "); continue; } if (fieldNames[i] == "EndData") { sb.Append("CreateTime").Append($" < @{i}").Append(" && "); continue; } sb.Append(fieldNames[i]).Append($" == @{i}").Append(" && "); } var lambdaStr = sb.ToString(); lambdaStr = lambdaStr.Substring(0, lambdaStr.Length - " && ".Length); // 構建表示式 var Expression = DynamicExpressionParser.ParseLambda<TEntity, bool>(new ParsingConfig() , false, lambdaStr, parameters.Values.ToArray()); return Expression; } /// <summary> /// 生成查詢字典 /// </summary> /// <param name="dto">物件</param> /// <param name="excludeFields">過濾器</param> /// <returns></returns> private Dictionary<string, object> GenerateParametersDictionary(object dto, Dictionary<string, object> excludeFields = null) { var ExcludeFields = excludeFields ?? new Dictionary<string, object>(); var type = dto.GetType(); var typeInfo = type; var properties = typeInfo.GetProperties(); var parameters = new Dictionary<string, object>(); foreach (var property in properties) { var propertyValue = property.GetValue(dto); if (propertyValue == null) continue; if (dto == null) continue; if (ExcludeFields.ContainsKey(property.Name)) continue; //DateTime型別較為特殊 if (property.PropertyType == typeof(DateTime) && propertyValue.ToString() == "0001/1/1 0:00:00") continue; if (parameters.ContainsKey(property.Name)) continue; parameters.Add(property.Name, propertyValue); } return parameters; } }

在專案中使用.

var LinqHelper = new LinqExpressionHelper<PayProcessRecord>();
var linq = LinqHelper.Build(reqPayTrade);   
var dbData = query.Find(linq);

結束