• [织梦吧]唯一域名:www.dedecms8.com,织梦DedeCMS学习平台.

当前位置: > 编程与数据库 > net编程 >

LINQ那些事儿(5)- 动态查询(2)

来源: www.dedecms8.com 编辑:织梦吧 时间:2012-06-27点击:

02 FROM (
03     SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[Cont
04 actTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[
05 Country], [t0].[Phone], [t0].[Fax]
06     FROM [dbo].[Customers] AS [t0]
07     WHERE [t0].[City] = @p0
08     UNION
09     SELECT [t1].[CustomerID], [t1].[CompanyName], [t1].[ContactName], [t1].[Cont
10 actTitle], [t1].[Address], [t1].[City], [t1].[Region], [t1].[PostalCode], [t1].[
11 Country], [t1].[Phone], [t1].[Fax]
12     FROM [dbo].[Customers] AS [t1]
13     WHERE [t1].[City] = @p1
14     ) AS [t2]

另外的方法就是是根据所有查询条件和查询值,给Where构造一个Expession。首先来看看Where的签名:

1 IQueryable<T> Where<T>(this IQueryable<T> source, Expression<Func<T, bool>> predicate)

对于这样一个Expression,如果你熟悉Expression Tree的构造方法,完全可以自己写。《C# 3.0 In Nutshell》的作者写了一个小巧的PrediateBuilder,可以帮助我们用lambda expression快速构造这样的expression:

01 var context = GenerateContext();
02 Expression<Func<Customer, bool>> filter = PredicateBuilder.False<Customer>();
03 string[] cities = { "London", "Paris" };
04
05 foreach (string item in cities)
06 {
07     string tmp = item;
08     filter = filter.Or(c => c.City == tmp);
09 }
10
11 context.Log = Console.Out;
12 context.Customers.Where(filter).Count().Dump();

输出的SQL也是我们期待的结果

1 SELECT COUNT(*) AS [value]
2 FROM [dbo].[Customers] AS [t0]
3 WHERE ([t0].[City] = @p0) OR ([t0].[City] = @p1)

最后,如果你对以前拼接SQL语句的方式还是念念不忘的话,可以去用Dynamic LINQ,参考SocttGu’s Blog。

About D8

  • ©2014 织梦吧(d8) DedeCMS学习交流平台
  • 唯一网址 www.DedeCMS8.com 网站地图
  • 联系我们 1170734538@qq.com ,  QQ