LINQ to SQL语句(23)之动态查询

http://www.prg-cn.com/article-4430-1.html

动态查询

有这样一个场景:应用程序可能会提供一个用户界面,用 户可以使用该用户界面指定一个或多个谓词来筛选数据。这种情况在编译时不知 道查询的细节,动态查询将十分有用。

在LINQ中,Lambda表达式是许多 标准查询运算符的基础,编译器创建lambda表达式以捕获基础查询方法(例如 Where、Select、Order By、Take While 以及其他方法)中定义的计算。表达式 目录树用于针对数据源的结构化查询,这些数据源实现IQueryable<T>。 例如,LINQ to SQL 提供程序实现 IQueryable<T>接口,用于查询关系数 据存储。C#和Visual Basic编译器会针对此类数据源的查询编译为代码,该代码 在运行时将生成一个表达式目录树。然后,查询提供程序可以遍历表达式目录树 数据结构,并将其转换为适合于数据源的查询语言。

表达式目录树在 LINQ中用于表示分配给类型为Expression<TDelegate>的变量的Lambda表 达式。还可用于创建动态LINQ查询。

System.Linq.Expressions命名空间 提供用于手动生成表达式目录树的API。Expression类包含创建特定类型的表达 式目录树节点的静态工厂方法,例如,ParameterExpression(表示一个已命名 的参数表达式)或 MethodCallExpression(表示一个方法调用)。编译器生成 的表达式目录树的根始终在类型Expression<TDelegate>的节点中,其中 TDelegate是包含至多五个输入参数的任何TDelegate委托;也就是说,其根节点 是表示一个lambda表达式。

下面几个例子描述如何使用表达式目录树来 创建动态LINQ查询。

1.Select

下面例子说明如何使用表达式树 依据 IQueryable 数据源构造一个动态查询,查询出每个顾客的ContactName, 并用GetCommand方法获取其生成SQL语句。

  1. //依据IQueryable数据 源构造一个查询
  2. IQueryable<Customer> custs = db.Customers;
  3. //组建一个表达式树来创建一个参数
  4. ParameterExpression param =
  5.   Expression.Parameter(typeof (Customer), "c");
  6. //组建表达式树:c.ContactName
  7. Expression selector = Expression.Property(param,
  8.   typeof (Customer).GetProperty("ContactName"));
  9. Expression pred = Expression.Lambda(selector, param);
  10. //组建表达式树:Select (c=>c.ContactName)
  11. Expression expr = Expression.Call(typeof (Queryable), "Select",
  12.   new Type[] { typeof (Customer), typeof(string) },
  13.   Expression.Constant(custs), pred);
  14. //使用表达式树来生成动态查询
  15. IQueryable<string> query = db.Customers.AsQueryable()
  16.    .Provider.CreateQuery<string>(expr);
  17. //使用GetCommand方法 获取SQL语句
  18. System.Data.Common.DbCommand cmd = db.GetCommand (query);
  19. Console.WriteLine(cmd.CommandText);
复制代码

生成的 SQL语句为:

  1. SELECT [t0].[ContactName] FROM [dbo]. [Customers] AS [t0]
复制代码

2.Where

下面一个例子是“搭建 ”Where用法来动态查询城市在伦敦的顾客。

  1. IQueryable<Customer> custs = db.Customers;
  2. // 创建一个参数c
  3. ParameterExpression param =
  4.    Expression.Parameter(typeof(Customer), "c");
  5. //c.City=="London"
  6. Expression left = Expression.Property(param,
  7.   typeof(Customer).GetProperty ("City"));
  8. Expression right = Expression.Constant ("London");
  9. Expression filter = Expression.Equal(left, right);
  10. Expression pred = Expression.Lambda(filter, param);
  11. //Where(c=>c.City=="London")
  12. Expression expr = Expression.Call(typeof(Queryable), "Where",
  13.   new Type[] { typeof(Customer) },
  14.   Expression.Constant(custs), pred);
  15. //生成动态查询
  16. IQueryable<Customer> query = db.Customers.AsQueryable()
  17.    .Provider.CreateQuery<Customer>(expr);
复制代码

生成的SQL 语句为:

  1. SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName],
  2. [t0].[ContactTitle], [t0].[Address], [t0]. [City], [t0].[Region],
  3. [t0].[PostalCode], [t0].[Country], [t0]. [Phone], [t0].[Fax]
  4. FROM [dbo].[Customers] AS [t0] WHERE [t0]. [City] = @p0
  5. -- @p0: Input NVarChar (Size = 6; Prec = 0; Scale = 0) [London]
复制代码

3.OrderBy本例既实现排序功能又实现了过滤功能。

  1. IQueryable<Customer> custs = db.Customers;
  2. //创建一个 参数c
  3. ParameterExpression param =
  4.   Expression.Parameter (typeof(Customer), "c");
  5. //c.City=="London"
  6. Expression left = Expression.Property(param,
  7.    typeof(Customer).GetProperty ("City"));
  8. Expression right = Expression.Constant ("London");
  9. Expression filter = Expression.Equal(left, right);
  10. Expression pred = Expression.Lambda(filter, param);
  11. //Where(c=>c.City=="London")
  12. MethodCallExpression whereCallExpression = Expression.Call(
  13.    typeof(Queryable), "Where",
  14.    new Type[] { typeof(Customer) },
  15.    Expression.Constant(custs), pred);
  16. //OrderBy(ContactName => ContactName)
  17. MethodCallExpression orderByCallExpression = Expression.Call(
  18.    typeof(Queryable), "OrderBy",
  19.    new Type[] { typeof(Customer), typeof(string) },
  20.    whereCallExpression,
  21.    Expression.Lambda(Expression.Property
  22.    (param, "ContactName"), param));
  23. //生成动态查询
  24. IQueryable<Customer> query = db.Customers.AsQueryable()
  25.    .Provider.CreateQuery<Customer> (orderByCallExpression);
复制代码

下面一张截图显示了怎么动态生成动 态查询的过程

生成的SQL语句为:

  1. SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName],
  2. [t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region],
  3. [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax]
  4. FROM [dbo].[Customers] AS [t0] WHERE [t0].[City] = @p0
  5. ORDER BY [t0].[ContactName]
  6. -- @p0: Input NVarChar (Size = 6; Prec = 0; Scale = 0) [London]
复制代码

4.Union

下面的例子使用表达式树动态查询顾客和雇员同在的城 市。

  1. //e.City
  2. IQueryable<Customer> custs = db.Customers;     
  3. ParameterExpression param1 =
  4. Expression.Parameter(typeof(Customer), "e");
  5. Expression left1 = Expression.Property(param1,
  6.   typeof (Customer).GetProperty("City"));
  7. Expression pred1 = Expression.Lambda(left1, param1);
  8. //c.City
  9. IQueryable<Employee> employees = db.Employees;
  10. ParameterExpression param2 =
  11. Expression.Parameter(typeof (Employee), "c");
  12. Expression left2 = Expression.Property(param2,
  13.   typeof(Employee).GetProperty ("City"));
  14. Expression pred2 = Expression.Lambda(left2, param2);
  15. //Select(e=>e.City)
  16. Expression expr1 = Expression.Call(typeof(Queryable), "Select",
  17.   new Type[] { typeof(Customer), typeof(string) },
  18.    Expression.Constant(custs), pred1);
  19. //Select(c=>c.City)
  20. Expression expr2 = Expression.Call(typeof(Queryable), "Select",
  21.   new Type[] { typeof(Employee), typeof (string) },
  22.   Expression.Constant(employees), pred2);
  23. //生 成动态查询
  24. IQueryable<string> q1 = db.Customers.AsQueryable()
  25.    .Provider.CreateQuery<string>(expr1);
  26. IQueryable<string> q2 = db.Employees.AsQueryable()
  27.    .Provider.CreateQuery<string>(expr2);
  28. //并集
  29. var q3 = q1.Union(q2);
复制代码

生成的SQL语句为:

  1. SELECT [t2].[City]
  2. FROM (
  3.   SELECT [t0].[City] FROM [dbo]. [Customers] AS [t0]
  4.   UNION
  5.   SELECT [t1].[City] FROM [dbo].[Employees] AS [t1]
  6.   ) AS [t2]
复制代码

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值