LINQ体验(17)——LINQ to SQL语句之动态查询

高级特性

本文介绍LINQ的高级特性,其包括大家都关心的动态查询的用法,另外简单提下ID标识这个知识。

动态查询

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

在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语句。

//依据IQueryable数据源构造一个查询
IQueryable<Customer> custs = db.Customers;
//组建一个表达式树来创建一个参数
ParameterExpression param = 
    Expression.Parameter(typeof(Customer), "c");
//组建表达式树:c.ContactName
Expression selector = Expression.Property(param,
    typeof(Customer).GetProperty("ContactName"));
Expression pred = Expression.Lambda(selector, param);
//组建表达式树:Select(c=>c.ContactName)
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);
//使用GetCommand方法获取SQL语句
System.Data.Common.DbCommand cmd = db.GetCommand(query);
Console.WriteLine(cmd.CommandText);

生成的SQL语句为:

SELECT [t0].[ContactName] FROM [dbo].[Customers] AS [t0]

2.Where

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

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")
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), typeof(string) }, 
    Expression.Constant(custs), pred1);
//Select(c=>c.City)
Expression expr2 = Expression.Call(typeof(Queryable), "Select", 
    new Type[] { typeof(Employee), typeof(string) }, 
    Expression.Constant(employees), pred2);
//生成动态查询
IQueryable<string> q1 = db.Customers.AsQueryable()
    .Provider.CreateQuery<string>(expr1);
IQueryable<string> q2 = db.Employees.AsQueryable()
    .Provider.CreateQuery<string>(expr2);
//并集
var q3 = q1.Union(q2);

生成的SQL语句为:

SELECT [t2].[City]
FROM (
    SELECT [t0].[City] FROM [dbo].[Customers] AS [t0]
    UNION
    SELECT [t1].[City] FROM [dbo].[Employees] AS [t1]
    ) AS [t2]

ID标识

在前面这一点没有说到,在这里作为高级特性单独说下ID标识。

这个例子说明我们存储一条新的记录时候,ContactID作为主键标识,系统自动分配,标识种子为1,所以每次自动加一。

//ContactID是主键ID,插入一条数据,系统自动分配ID
Contact con = new Contact()
{
    CompanyName = "New Era",
    Phone = "(123)-456-7890"
};
db.Contacts.InsertOnSubmit(con);
db.SubmitChanges();

本系列链接:LINQ体验系列文章导航

LINQ推荐资源

LINQ专题:http://kb.cnblogs.com/zt/linq/ 关于LINQ方方面面的入门、进阶、深入的文章。
LINQ小组:http://space.cnblogs.com/group/linq/ 学习中遇到什么问题或者疑问提问的好地方。


作者:李永京YJingLee's Blog
出处:http://lyj.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

Tag标签: LINQ,LINQ to SQL
posted @ 2008-03-25 22:47 李永京 阅读(9867) 评论(33)  编辑 收藏 网摘 所属分类: LINQ

  回复  引用    
#1楼2008-03-26 06:54 | 过客007[未注册用户]
LINQ在这方面还比较麻烦,相反一些拼SQL的类库语法,比这个要强很多.
  回复  引用  查看    
#2楼2008-03-26 06:55 | 生鱼片      
博主能否整理出一个这系列的知识点的代码下载,可以收藏下
  回复  引用  查看    
#3楼2008-03-26 07:47 | 隨風.NET      
先顶再看
  回复  引用    
#4楼2008-03-26 07:54 | JuzzPig[未注册用户]
var query=ctx.table.Where(x=>x.name=="test");
if xxxx
query=query.where(x=>x.sex==1)



这样是不是更简单点?

  回复  引用  查看    
#5楼2008-03-26 08:06 | 小庄      
用微软提供的System.Linq.Dynamic方便点。
  回复  引用    
#6楼2008-03-26 08:13 | mmkk[未注册用户]
实际上, 如果你将IQueryable暴露到表现层的话, 由于LINQ to SQL具有延迟执行的功能, 并不需要这么复杂的做法, 类似JuzzPig的做法即可. 通常需要动态执行的情况是你已经有封装好的Business Method接受参数并且返回List<T>或者T之类的, 不过使用MS提供的Dynamic.cs更方便和简单一点:
\Samples\1033\CSharpSamples\LinqSamples\DynamicQuery\DynamicQuery\Dynamic.cs

  回复  引用  查看    
#8楼2008-03-26 10:50 | Jeffrey Zhao      
@隨風.NET
不会。

  回复  引用  查看    
#9楼2008-03-26 10:51 | Jeffrey Zhao      
@mmkk
的确。不过IQueryable不适合暴露到太多,因为还有DataLoadOptions控制不了……

  回复  引用  查看    
#10楼[楼主]2008-03-26 12:08 | 李永京      
@过客007
确实比较麻烦,不过既然LINQ有了这个功能,还是在这里系统的说下了。我个人比较看好ASP.NET3.5 Extensions提供System.Linq.Dynamic来使用动态查询。

  回复  引用  查看    
#11楼[楼主]2008-03-26 12:13 | 李永京      
@生鱼片
这个系列的代码全部来自微软提供的101例子。具体下载地址为:http://code.msdn.microsoft.com/csharpsamples" target="_new">http://code.msdn.microsoft.com/csharpsamples

  回复  引用  查看    
#12楼[楼主]2008-03-26 12:20 | 李永京      
@小庄
我个人比较看好ASP.NET3.5 Extensions提供System.Linq.Dynamic来使用动态查询。而不用这样的写法。o(∩_∩)o...

  回复  引用  查看    
#13楼[楼主]2008-03-26 12:21 | 李永京      
@mmkk
@隨風.NET
确实不好控制,呵呵

  回复  引用  查看    
#14楼[楼主]2008-03-26 12:22 | 李永京      
@Jeffrey Zhao
谢谢老赵支持!在这里分享您的知识!(*^__^*) 嘻嘻……

  回复  引用  查看    
#15楼2008-03-26 16:37 | 隨風.NET      
linq 下如何批量删除和批量更新 比较好?
  回复  引用  查看    
#16楼[楼主]2008-03-26 16:44 | 李永京      
@隨風.NET
关于这个你看看Jeffrey Zhao一篇文章:扩展LINQ to SQL:使用Lambda Expression批量删除数据。非常好
地址为:http://www.cnblogs.com/JeffreyZhao/archive/2008/03/05/LINQ-to-SQL-Batch-Delete-Extension.html" target="_new">http://www.cnblogs.com/JeffreyZhao/archive/2008/03/05/LINQ-to-SQL-Batch-Delete-Extension.html

  回复  引用    
#17楼2008-04-18 18:10 | 啊潘[未注册用户]
var query=ctx.table.Where(x=>x.name=="test");
if xxxx
query=query.where(x=>x.sex==1)
这样是不是更简单点?
--------------------------
这样是简单,但是在分层中,dao底层无法得知table是什么。

  回复  引用    
#18楼2008-04-20 10:32 | java2[未注册用户]
楼主也要用到<Customer>的泛型,相当于也是需要确实是哪个Table
  回复  引用  查看    
#19楼[楼主]2008-04-20 10:37 | 李永京      
@啊潘
@java2
你们讨论哪方面的内容啊,LINQ to SQL 提供程序实现 IQueryable<T>接口,这些数据源可以实现IQueryable<T>。我当然用IQueryable<Customer>了。

  回复  引用    
#20楼2008-07-02 23:27 | pcvcccc[未注册用户]
搞了半天还不知道表达式目录树是什么玩意??


//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), typeof(string) },
Expression.Constant(custs), pred1);
//Select(c=>c.City)
Expression expr2 = Expression.Call(typeof(Queryable), "Select",
new Type[] { typeof(Employee), typeof(string) },
Expression.Constant(employees), pred2);
//生成动态查询
IQueryable<string> q1 = db.Customers.AsQueryable()
.Provider.CreateQuery<string>(expr1);
IQueryable<string> q2 = db.Employees.AsQueryable()
.Provider.CreateQuery<string>(expr2);
//并集
var q3 = q1.Union(q2);生成的SQL语句为:

SELECT [t2].[City]
FROM (
SELECT [t0].[City] FROM [dbo].[Customers] AS [t0]
UNION
SELECT [t1].[City] FROM [dbo].[Employees] AS [t1]
) AS [t2]



那么长的代码才生成那样的sql?????

  回复  引用    
#21楼2008-07-02 23:27 | pcvcccc[未注册用户]
何必????????????????
  回复  引用  查看    
#22楼[楼主]2008-07-11 20:59 | 李永京      
@pcvcccc
不好意思,一直没有时间上网,没得及时回复。
上面代码就是这个意思,动态生成SQL

  回复  引用    
#23楼2008-07-22 12:50 | Memory[未注册用户]
好像有点麻烦....
在一个查询中添加一个where条件 并且选择出一个表中的部分列,怎么弄比较好?
呵呵

  回复  引用    
#24楼2008-07-27 06:22 | zycpro[未注册用户]
本例既实现排序功能又实现了过滤功能(过滤条件为StartsWith,根据需要自己选)
IQueryable<Customer> custs = db.Customers;
//创建一个参数c
ParameterExpression param =
Expression.Parameter(typeof(Customer), "c");
//c.City.StartsWith("London")
Expression left = Expression.Property(param,
typeof(Customer).GetProperty("City"));
Expression right = Expression.Constant("London");
Expression filter = Expression.Call(left, typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }), right); //原来是 Expression.Equal(left, right);
Expression pred = Expression.Lambda(filter, param);
//Where(c=>c.City.StartsWith("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);

本例只更改了Lambda表达式,为后学者提供方面

  回复  引用  查看    
#25楼[楼主]2008-07-28 23:02 | 李永京      
@zycpro
谢谢提醒

  回复  引用  查看    
#26楼2008-08-04 13:57 | SZW      
用where (需要筛选 == true)?c.字段==筛选条件 : true。linq会自动生成select中的case语句,总体效率应该比这么做要高,而且代码一目了然。
  回复  引用  查看    
#28楼[楼主]2008-08-09 23:18 | 李永京      
@SZW
en

  回复  引用    
#29楼2008-08-18 16:15 | xxxxxxxxxx[未注册用户]
什么LINQ,一点用都没有,反而把简单的问题搞复杂了。用SQL语句不是挺好吗,变来变去的,越变越复杂。
  回复  引用    
#30楼2009-01-11 16:04 | blfr[未注册用户]
如题,整了快两个月还搞不定,就是表的列名未变量,经dropdownlist选择传递where参数啊
  回复  引用    
#31楼2009-01-11 16:05 | blfr[未注册用户]
用where (变量 == 变量)怎么写?????
  回复  引用    
#32楼2009-04-13 11:15 | 臧亢[未注册用户]
// DataContext takes a connection string.
DataContext db = new DataContext(@"c:\Northwnd.mdf");

// Get a typed table to run queries.
Table<Customer> Customers = db.GetTable<Customer>();

// Query for customers from London.
var query =
from cust in Customers
where cust.City == "London"
select cust;

foreach (var cust in query)
Console.WriteLine("id = {0}, City = {1}", cust.CustomerID, cust.City);


msdn的这段代码中db.GetTable<Customer>()这个方法的参数是数据库的表吗?为什么总是出现未映射为表?是什么原因呢?




发表评论

昵称: [登录] [注册]

主页:

邮箱:(仅博主可见)

评论内容:

  登录  注册

[使用Ctrl+Enter键快速提交评论]

0 1122157




相关文章:

相关链接: