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

结束

猜你喜欢

转载自www.cnblogs.com/SantiagoZhang/p/10185373.html
今日推荐