C# 反射 表达式树 模糊搜索

反射实体T,非datetime字段反射获取表达式树

  public static Expression<Func<T, bool>> GetSearchExpression<T>(string SearchString)

        {

            Expression<Func<T, bool>> filter = null;

            if (string.IsNullOrEmpty(SearchString)) return null;

            var left = Expression.Parameter(typeof(T), "m");

            Expression expression = Expression.Constant(false);

            T obj = default(T);

            var type = typeof(T);

            obj = (T)Activator.CreateInstance(type);

            var propertyInfos = type.GetProperties();

            foreach (var propertyInfo in propertyInfos)

            {

                if (propertyInfo.Name.ToLower() == "id" || propertyInfo.PropertyType == typeof(DateTime)) continue;

                Expression tostring = Expression.Call

         (

             Expression.Property(left, typeof(T).GetProperty(propertyInfo.Name).Name),

           typeof(object).GetMethod("ToString", new Type[] { })

         );

                Expression right = Expression.Call

                      (

                          tostring,

                        typeof(string).GetMethod("Contains", new Type[] { typeof(string) }),

                        Expression.Constant(SearchString)

                      );

                expression = Expression.Or(right, expression);

            }

            filter = Expression.Lambda<Func<T, bool>>(expression, new[] { left });

            return filter;

        }
上一篇:SpringBoot+Maven 多模块项目的构建、运行、打包


下一篇:Hibernate逍遥游记-第10章 映射继承关系-001继承关系树中的每个具体类对应一个表