• 00
  • :
  • 00
  • :
  • 00

EF Linq动态条件查询

   if (parm.Filters != null && parm.Filters.Count > 0)
            {
                Expression expression = null;
                ParameterExpression param = Expression.Parameter(typeof(View_spu), "w");//w=>
                foreach (var obj in parm.Filters)
                {
                    Expression dlh_left = Expression.Property(param, typeof(View_spu).GetProperty(nameof(View_spu.dlh)));  //c.DataSourceName
                    Expression dlh_right = Expression.Constant(obj.dlh);
                    BinaryExpression dlh_filter = Expression.Equal(dlh_left, dlh_right);

                    Expression xlh_left = Expression.Property(param, typeof(View_spu).GetProperty(nameof(View_spu.xlh)));  //c.DataSourceName
                    Expression xlh_right = Expression.Constant(obj.xlh);
                    BinaryExpression xlh_filter = Expression.Equal(xlh_left, xlh_right);


                    var filter = Expression.And(xlh_filter, xlh_filter);

                    if (expression == null)
                    {
                        expression = filter;
                    }

                    else
                        expression = Expression.Or(filter, expression);
                }

                if (expression != null)
                {
                    Expression<Func<View_spu, bool>> finalExpression = Expression.Lambda<Func<View_spu, bool>>(expression, param);
                    query = query.Where(finalExpression);
                }
            }

 

posted @ 2020-09-09 10:39  Garson_Zhang  阅读(343)  评论(0编辑  收藏  举报