다음을 통해 공유


방법: 쿼리 저장 및 재사용

구조적으로 유사한 쿼리를 여러 번 실행하는 애플리케이션이 있는 경우 쿼리를 한 번 컴파일하고 다른 매개 변수를 사용하여 여러 번 실행하여 성능을 높일 수 있습니다. 예를 들어 애플리케이션은 특정 도시에 있는 모든 고객을 검색해야 할 수 있습니다. 여기서 런타임 시 사용자가 양식으로 도시를 지정합니다. 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

참고하십시오