如何:存储和重用查询

如果应用程序多次执行结构相似的查询,则通常可以通过编译查询一次并使用不同参数多次执行查询来提高性能。 例如,应用程序可能必须检索特定城市中的所有客户,其中城市在运行时由用户以表单形式指定。 LINQ to SQL 支持出于此目的使用 已编译的查询

注释

此用法模式表示编译查询的最常见用途。 其他方法是可能的。 例如,编译的查询可以存储为扩展设计器生成的代码的分部类上的静态成员。

示例 1

在许多情况下,你可能希望跨线程边界重复使用查询。 在这种情况下,将编译的查询存储在静态变量中尤其有效。 下面的代码示例假定有一个类 Queries 用于存储已编译查询,并且假定 Northwind 类表示一个强类型 DataContext

public static Func<Northwnd, string, IQueryable<Customer>>
    CustomersByCity =
        CompiledQuery.Compile((Northwnd db, string city) =>
            from c in db.Customers where c.City == city select c);

public static Func<Northwnd, string, IQueryable<Customer>>
    CustomersById = CompiledQuery.Compile((Northwnd db,
    string id) => db.Customers.Where(c => c.CustomerID == id));
Class Queries

    Public Shared CustomersByCity As _
        Func(Of Northwnd, String, IQueryable(Of Customer)) = _
            CompiledQuery.Compile(Function(db As Northwnd, _
    city As String) _
        From c In db.Customers Where c.City = city Select c)

    Public Shared CustomersById As _
        Func(Of Northwnd, String, IQueryable(Of Customer)) = _
            CompiledQuery.Compile(Function(db As Northwnd, _
    id As String) _
        db.Customers.Where(Function(c) c.CustomerID = id))

End Class
// The following example invokes such a compiled query in the main
// program.

public IEnumerable<Customer> GetCustomersByCity(string city)
{
    var myDb = GetNorthwind();
    return Queries.CustomersByCity(myDb, city);
}
' The following example invokes such a compiled query in the main
' program
Public Function GetCustomersByCity(ByVal city As String) As _
    IEnumerable(Of Customer)

    Dim myDb = GetNorthwind()
    Return Queries.CustomersByCity(myDb, city)
End Function

示例 2

当前无法存储返回 匿名类型的查询(静态变量),因为类型没有要作为泛型参数提供的名称。 以下示例演示如何通过创建可表示结果的类型,然后将其用作泛型参数来解决此问题。

class SimpleCustomer
{
    public string ContactName { get; set; }
}

class Queries2
{
    public static Func<Northwnd, string, IEnumerable<SimpleCustomer>> CustomersByCity =
        CompiledQuery.Compile<Northwnd, string, IEnumerable<SimpleCustomer>>(
        (Northwnd db, string city) =>
        from c in db.Customers
        where c.City == city
        select new SimpleCustomer { ContactName = c.ContactName });
}
Class SimpleCustomer
    Private _ContactName As String
    Public Property ContactName() As String
        Get
            Return _ContactName
        End Get
        Set(ByVal value As String)
            _ContactName = value
        End Set
    End Property
End Class

Class Queries2
    Public Shared CustomersByCity As Func(Of Northwnd, String, IEnumerable(Of SimpleCustomer)) = _
        CompiledQuery.Compile(Of Northwnd, String, IEnumerable(Of SimpleCustomer))( _
        Function(db As Northwnd, city As String) _
        From c In db.Customers _
        Where c.City = city _
        Select New SimpleCustomer With {.ContactName = c.ContactName})
End Class

另请参阅