don")
Expression expr = Expression.Call(typeof(Queryable), "Where",
new Type[] { typeof(Customer) },
Expression.Constant(custs), pred);
//生成动态查询
IQueryable<Customer> query = db.Customers.AsQueryable()
.Provider.CreateQuery<Customer>(expr);
生成的SQL 语句为:
SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName],
[t0].[ContactTitle], [t0].[Address], [t0]. [City], [t0].[Region],
[t0].[PostalCode], [t0].[Country], [t0]. [Phone], [t0].[Fax]
FROM [dbo].[Customers] AS [t0] WHERE [t0]. [City] = @p0
-- @p0: Input NVarChar (Size = 6; Prec = 0; Scale = 0) [London]
3.OrderBy
本例既实现排序功能又实现了过滤功 能。
IQueryable<Customer> custs = db.Customers;
//创建一个参数c
ParameterExpression param =
Expression.Parameter(typeof(Customer), "c");
//c.City=="London"
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);
//Where(c=>c.City=="London")
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);
下面一张截图显示了怎么动态生成动 态查询的过程
生成的SQL语句为:
SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName],
[t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region],
[t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax]
FROM [dbo].[Customers] AS [t0] WHERE [t0].[City] = @p0
ORDER BY [t0].[ContactName]
-- @p0: Input NVarChar (Size = 6; Prec = 0; Scale = 0) [London]
4.Union
下面的例子使用表达式树动态查询顾客和雇员同在的 城市。
//e.City
IQueryable<Customer> custs = db.Customers;
ParameterExpression param1 =
Expression.Parameter(typeof(Customer), "e");
Expression left1 = Expression.Property(param1,
typeof (Customer).GetProperty("City"));
Expression pred1 = Expression.Lambda(left1, param1);
//c.City
IQueryable<Employee> employees = db.Employees;
ParameterExpression param2 =
Expression.Parameter(typeof (Employee), "c");
Expression left2 = Expression.Property(param2,
typeof(Employee).GetProperty ("City"));
Expression pred2 = Expression.Lambda(left2, param2);
//Select(e=>e.City)
Expression expr1 = Expression.Call(typeof(Queryable), "Select",
new Type[] { typeof(Customer), type
|