日期:2014-05-20 浏览次数:20844 次
IQueryable<Customer> custs = db.Customers; 改成IQueryable<Customer> custs = db.Customers.Where(c=>c.City=="London");//先筛选再动态查询 ParameterExpression param = Expression.Parameter(typeof(Customer), "c"); Expression selector = Expression.Property(param, typeof(Customer).GetProperty("ContactName")); Expression pred = Expression.Lambda(selector, param); Expression expr = Expression.Call(typeof(Queryable), "Select", new Type[] { typeof(Customer), typeof(string) }, Expression.Constant(custs), pred); IQueryable<string> query = db.Customers.AsQueryable() .Provider.CreateQuery<string>(expr); //经过上面的筛选调试结果为空?请问能否这样? System.Data.Common.DbCommand cmd = db.GetCommand(query); Console.WriteLine(cmd.CommandText); IQueryable<Customer> custs = db.Customers; ParameterExpression param = Expression.Parameter(typeof(Customer), "c"); Expression left = Expression.Property(param, typeof(Customer).GetProperty("City")); Expression right = Expression.Constant("London"); Expression filter = Expression.Equal(left, right); Expression pred = Expression.Lambda(filter, param); MethodCallExpression whereCallExpression = Expression.Call( typeof(Queryable), "Where", new Type[] { typeof(Customer) }, Expression.Constant(custs), pred); //OrderBy(ContactName => ContactName) MethodCallExpression orderByCallExpression = Expression.Call( typeof(Queryable), "OrderBy", new Type[] { typeof(Customer), typeof(string) }, whereCallExpression, Expression.Lambda(Expression.Property (param, "ContactName"), param)); //生成动态查询 IQueryable<Customer> query = db.Customers.AsQueryable() .Provider.CreateQuery<Customer>(orderByCallExpression);