Linq To Sql进阶系列(七)动态查询续及CLR与SQL在某些细节上的差别
[2] Linq To Sql进阶系列(七)动态查询续及CLR与SQL在某些细节上的差别
[3] Linq To Sql进阶系列(七)动态查询续及CLR与SQL在某些细节上的差别
[4] Linq To Sql进阶系列(七)动态查询续及CLR与SQL在某些细节上的差别
系列文章导航:
Linq To Sql进阶系列(四)User Define Function篇
Linq To Sql进阶系列(五)Store Procedure篇
Linq To Sql进阶系列(六)用object的动态查询与保存log篇
Linq To Sql进阶系列(七)动态查询续及CLR与SQL在某些细节上的差别
在这里,首先检查输入的参数是否为null。扩展方法其实是按静态方法执行的。它和静态方法唯一不同的就是系统自动为其加了一个Attribute,而这个Attribute只能通过在第一个参数加this关键字才能获得。而后,在影射类型上,修改后的函数只支持数值型和string型。其原因就是像imager等并不支持条件查询。为了简化,我们只支持数值型和string型。这里最大的变化莫过于支持or条件了。调用Expression.And或Expression.Or就可以了。还有一个变化就是ParameterExpression对象和Expression<Func<TEntity, bool>>被移出了foreach循环。这样,提高了效率,只是在最后才去生成条件。
而实际上,大家大多使用是and条件,那再重载一个方法。




我们再来测试一下
Northwind db = new Northwind();
db.Log = Console.Out;
Customer cu = new Customer { City = "London", Country = "UK" };
var q0 = db.Customers.Find(cu).ToList();
var q1 = db.Customers.OrderBy(c=>c.Country).Find(cu, false).ToList();
var q2 = Extension.Find(db.Customers.OrderBy(c => c.CustomerID), cu).ToList();
大家可以看到,它们和系统定义方法一样使用,可以接在任何满足条件的语句后面。第三个例子直接就用的static方法的形式。从第三个例子,我们可以看出,extension methods和static methods差别其实不大。
它们生成的sql为

[t0].[Address







[t0].[Address









[t0].[Address





