查询数据的过程中,如果需要根据某些条件的存在与否来查询,那么动态生成条件是必不可少的:
//构造一个查询及表达式树 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;