存储和重用查询
当您的应用程序多次执行结构上相似的查询时,您通常可以通过如下方法提高性能:编译此查询一次,然后用不同的参数执行它若干次。例如,应用程序可能需要检索位于特定城市的所有客户,其中此城市是在运行时由用户在窗体中指定的。ALinq 支持使用已编译查询来实现此目的。
示例
private static Func<NorthwindDatabase, string, IQueryable<Customer>> CustomersByCity =
ALinq.CompiledQuery.Compile((NorthwindDatabase db, string city) =>
from c in db.Customers
where c.City == city
select c);
private static Func<NorthwindDatabase, string, Customer> CustomersById =
ALinq.CompiledQuery.Compile((NorthwindDatabase db, string id) =>
db.Customers.Where(c => c.CustomerID == id).First());
在很多情况下,您可能需要跨线程边界重复使用查询。在这种情况下,将已编译查询存储在静态变量中特别有效。下面的代码示例采用设计用于存储已编译查询的 Queries,并采用表示强类型化 DataContext 的 NorthwindDatabase 类
var customers = CustomersByCity(db, "London").ToList();
Assert.IsTrue(customers.Count() > 0);
var id = customers.First().CustomerID;
var customer = CustomersById(db, id);
Assert.AreEqual("London", customer.City);