Share via


방법: 쿼리 저장 및 다시 사용(LINQ to SQL)

업데이트: November 2007

구조적으로 유사한 쿼리를 여러 번 실행하는 응용 프로그램이 있는 경우 일반적으로 쿼리를 한 번 컴파일하고 다른 매개 변수와 함께 여러 번 실행하여 성능을 향상시킬 수 있습니다. 예를 들어, 특정 도시에 있는 모든 고객을 응용 프로그램에서 검색해야 하고 런타임에 사용자가 폼에서 도시를 지정하는 경우를 가정할 수 있습니다. 이러한 경우를 위해 LINQ to SQL에서는 컴파일된 쿼리 사용이 지원됩니다.

참고:

이 사용 패턴은 컴파일된 쿼리가 사용되는 가장 일반적인 방식입니다. 다른 방법도 가능합니다. 예를 들어, 디자이너에 의해 생성된 코드를 확장하는 partial 클래스에서 컴파일된 쿼리를 정적 멤버로 저장할 수 있습니다.

예제

대부분의 시나리오에서는 스레드 경계를 넘어 쿼리를 다시 사용할 수 있습니다. 이러한 경우 컴파일된 쿼리를 정적 변수에 저장하는 것이 특히 효과적입니다. 다음 코드 예제에서는 컴파일된 쿼리를 저장하도록 디자인된 Queries 클래스를 가정하고 강력한 형식의 DataContext를 나타내는 Northwind 클래스를 가정합니다.

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
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));
' 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
// 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);
}

제네릭 인수로 제공할 이름이 형식에 없기 때문에 현재는 익명 형식을 반환하는 쿼리를 정적 변수에 저장할 수 없습니다. 다음 예제에서는 결과를 나타낼 수 있는 형식을 만든 다음 이를 제네릭 인수로 사용하여 이 문제를 해결할 수 있는 방법을 보여 줍니다.

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
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 });
}

참고 항목

참조

CompiledQuery

기타 리소스

LINQ to SQL의 쿼리 개념

데이터베이스 쿼리(LINQ to SQL)