共用方式為


作法:儲存和重複使用查詢

當您的應用程式會多次執行結構類似的查詢時,您藉由編譯查詢一次並使用不同的參數加以執行數次,通常可以提高效能。 例如,應用程式可能必須擷取位於特定城市的所有客戶,該城市是使用者於執行階段在表單中指定。 LINQ to SQL 支援就此目的使用「已編譯查詢」

注意

這種模式的使用方式代表已編譯查詢的最常見用途。 其他方法也有可能。 例如,在可擴充設計工具所產生之程式碼的部分類別中,已編譯查詢可以儲存為靜態成員。

範例 1

在許多情況下,您會想要跨越執行緒界限重複使用查詢。 在此情況下,以靜態變數儲存已編譯查詢特別有效。 下列程式碼範例採用了設計用來儲存已編譯查詢的 Queries 類別,並採用表示強型別 DataContext 的 Northwind 類別。

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

另請參閱