欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Linq中动态生成查询

程序员文章站 2022-07-04 16:18:39
...

查询数据的过程中,如果需要根据某些条件的存在与否来查询,那么动态生成条件是必不可少的:

            //构造一个查询及表达式树
            IQueryable qy = cont.Category;
            ParameterExpression param = Expression.Parameter(typeof(Category), "c");

            //条件1
            Expression right = Expression.Constant(10);
            Expression left = Expression.Property(param, typeof(Category).GetProperty("ID"));
            Expression p1 = Expression.Equal(left, right);

            //组合条件2
            if (checkBox1.Checked)
            {
                Expression right1 = Expression.Constant(11);
                Expression filter1 = Expression.Equal(left, right1);
                p1 = Expression.Or(p1, filter1);
            }

            Expression pred = Expression.Lambda(p1, param);

            //生成查询
            Expression expr = Expression.Call(typeof(Queryable), "Where", new Type[] { typeof(Category) }, Expression.Constant(qy), pred);
            IQueryable<Category> query = cont.Category.AsQueryable().Provider.CreateQuery<Category>(expr);
            this.dataGridView1.DataSource = query;