Share via


쿼리 작성기 메서드(Entity Framework)

ObjectQuery 클래스는 개념적 모델에 대해 LINQ to Entities 쿼리와 Entity SQL 쿼리를 모두 지원합니다. 또한 ObjectQuery는 Entity SQL 과 동일한 쿼리 명령을 순차적으로 생성하는 데 사용할 수 있는 쿼리 작성기 메서드 집합을 구현합니다. 다음은 ObjectQuery의 쿼리 작성기 메서드와 이와 동일한 Entity SQL 문입니다.

ObjectQuery 메서드 Entity SQL 문

Distinct

DISTINCT

Except

EXCEPT

GroupBy

GROUP BY

Intersect

INTERSECT

OfType

OFTYPE

OrderBy

ORDER BY

Select

SELECT

SelectValue

SELECT VALUE

Skip

SKIP

Top

TOPLIMIT

Union

UNION

UnionAll

UNION ALL

Where

WHERE

각 쿼리 작성기 메서드에서는 ObjectQuery의 새 인스턴스를 반환합니다. 따라서 쿼리 결과 집합이 이전 ObjectQuery 인스턴스의 시퀀스 작업을 기준으로 하는 쿼리를 생성할 수 있습니다. 다음 예제에서는 Where 메서드를 사용하여 ProductID에 따라 반환된 Product 개체를 필터링하는 방법을 보여 줍니다.

' Return Product objects with the specified ID. 
Dim query As ObjectQuery(Of Product) = context.Products.Where("it.ProductID = @product", New ObjectParameter("product", productId))
// Return Product objects with the specified ID.
ObjectQuery<Product> query =
    context.Products
    .Where("it.ProductID = @product",
    new ObjectParameter("product", productId));

ObjectQuery에서 IQueryableIEnumerable을 구현하므로 ObjectQuery에서 구현된 쿼리 작성기 메서드를 First, Count 등의 LINQ 관련 표준 쿼리 연산자 메서드와 결합할 수 있습니다. LINQ 연산자는 쿼리 작성기 메서드와 달리 ObjectQuery를 반환하지 않습니다. 자세한 내용은 Visual Studio 2008 설명서의 표준 쿼리 연산자 개요 항목을 참조하십시오.

데이터 선택

ObjectQuery에서는 기본적으로 특정 형식의 엔터티 개체를 0개 이상 반환합니다. Where, OrderBy 등의 쿼리 메서드를 순차적으로 호출하면 원래 ObjectQuery에서 반환된 개체 컬렉션에 영향을 줍니다. Select, GroupBy 등의 일부 메서드에서는 데이터의 프로젝션을 엔터티 형식 대신 DbDataRecord로 반환합니다. 자세한 내용은 개체 쿼리(Entity Framework)를 참조하십시오. 다음 예제에서는 중첩된 SalesOrderHeader 엔터티 형식에 포함된 DbDataRecord 개체의 컬렉션을 반환합니다.

' Define a query that returns a nested 
' DbDataRecord for the projection. 
Dim query As ObjectQuery(Of DbDataRecord) = context.Contacts.Select("it.FirstName, it.LastName, it.SalesOrderHeaders") _
                                            .Where("it.LastName = @ln", New ObjectParameter("ln", lastName))
// Define a query that returns a nested 
// DbDataRecord for the projection.
ObjectQuery<DbDataRecord> query =
    context.Contacts.Select("it.FirstName, "
        + "it.LastName, it.SalesOrderHeaders")
    .Where("it.LastName = @ln", new ObjectParameter("ln", lastName));

쿼리 작성기 메서드는 순차적으로 적용되지만 Entity SQL 에서 지원되는 것과 동일한 형식의 중첩된 하위 쿼리를 생성할 수 있습니다. 그렇게 하려면 하위 쿼리를 메서드 내에서 Entity SQL 로 포함해야 합니다. 다음 예제에서는 Select 메서드 내에서 Entity SQL SELECT 하위 쿼리를 사용하여, 결과 집합에서 중첩되고 성의 첫 번째 문자를 기준으로 사전순으로 정렬된 LastName 레코드를 포함합니다.

' Define the query with a GROUP BY clause that returns 
' a set of nested LastName records grouped by first letter. 
Dim query As ObjectQuery(Of DbDataRecord) = _
    context.Contacts.GroupBy("SUBSTRING(it.LastName, 1, 1) AS ln", "ln") _
    .Select("it.ln AS ln, (SELECT c1.LastName FROM AdventureWorksEntities.Contacts AS c1 " & _
            "WHERE SubString(c1.LastName, 1, 1) = it.ln) AS CONTACT").OrderBy("it.ln")
// Define the query with a GROUP BY clause that returns
// a set of nested LastName records grouped by first letter.
ObjectQuery<DbDataRecord> query =
    context.Contacts
    .GroupBy("SUBSTRING(it.LastName, 1, 1) AS ln", "ln")
    .Select("it.ln AS ln, (SELECT c1.LastName " +
    "FROM AdventureWorksEntities.Contacts AS c1 " +
    "WHERE SubString(c1.LastName, 1, 1) = it.ln) AS CONTACT")
    .OrderBy("it.ln");
Bb896238.note(ko-kr,VS.100).gif참고:
ObjectQuery에서 생성되는 데이터 소스 명령을 보려면 ToTraceString 메서드를 사용하십시오.자세한 내용은 개체 쿼리(Entity Framework)를 참조하십시오.

별칭

쿼리 작성기 메서드는 순차적으로 적용되어 누적 쿼리 명령을 생성합니다. 즉, 현재 ObjectQuery 명령은 현재 메서드가 적용되는 하위 쿼리와 같이 처리됩니다.

Bb896238.note(ko-kr,VS.100).gif참고:
CommandText 속성은 ObjectQuery 인스턴스에 대한 명령을 반환합니다.

쿼리 작성기 메서드에서 별칭을 사용하여 현재 ObjectQuery 명령을 참조할 수 있습니다. 기본적으로 "it" 문자열은 다음 예제에서와 같이 현재 명령을 나타내는 별칭입니다.

' Return Product objects with a standard cost 
' above 10 dollars. 
Dim cost = 10
Dim productQuery As ObjectQuery(Of Product) = context.Products.Where("it.StandardCost > @cost")
productQuery.Parameters.Add(New ObjectParameter("cost", cost))
int cost = 10;
// Return Product objects with a standard cost
// above 10 dollars.
ObjectQuery<Product> productQuery =
    context.Products
    .Where("it.StandardCost > @cost", new ObjectParameter("cost", cost));

ObjectQueryName 속성을 설정하면 해당 값은 후속 메서드에서 별칭이 됩니다. 다음 예제에서는 ObjectQuery의 이름을 "product"로 설정한 다음 후속 OrderBy 메서드에서 이 별칭을 사용하여 이전 명령을 확장합니다.

' Return Product objects with a standard cost 
' above 10 dollars. 
Dim cost = 10
Dim productQuery As ObjectQuery(Of Product) = context.Products.Where("it.StandardCost > @cost")
productQuery.Parameters.Add(New ObjectParameter("cost", cost))

' Set the Name property for the query and then 
' use that name as the alias in the subsequent 
' OrderBy method. 
productQuery.Name = "product"
Dim filteredProduct As ObjectQuery(Of Product) = productQuery.OrderBy("product.ProductID")
int cost = 10;
// Return Product objects with a standard cost
// above 10 dollars.
ObjectQuery<Product> productQuery =
    context.Products
    .Where("it.StandardCost > @cost", new ObjectParameter("cost", cost));

// Set the Name property for the query and then 
// use that name as the alias in the subsequent 
// OrderBy method.
productQuery.Name = "product";
ObjectQuery<Product> filteredProduct = productQuery
    .OrderBy("product.ProductID");

매개 변수

Entity SQL 문자열 입력을 받아들이는 모든 쿼리 작성기 메서드는 또한 매개 변수가 있는 쿼리를 지원합니다. Entity SQL 의 매개 변수 이름은 at(@) 기호를 접두사로 사용하여 쿼리 식에 정의됩니다. 자세한 내용은 매개 변수(Entity SQL)를 참조하십시오. 매개 변수는 ObjectParameter 인스턴스의 배열로서 쿼리 작성기 메서드에 전달됩니다. 다음 예제에서는 두 개의 매개 변수를 Where 메서드에 전달합니다.

' Get the contacts with the specified name. 
Dim contactQuery As ObjectQuery(Of Contact) = context.Contacts.Where("it.LastName = @ln AND it.FirstName = @fn", _
                                                 New ObjectParameter("ln", lastName), New ObjectParameter("fn", firstName))
// Get the contacts with the specified name.
ObjectQuery<Contact> contactQuery = context.Contacts
    .Where("it.LastName = @ln AND it.FirstName = @fn",
    new ObjectParameter("ln", lastName),
    new ObjectParameter("fn", firstName));

매개 변수 사용에 대한 고려 사항

쿼리 작성기 메서드와 함께 매개 변수를 사용할 때 다음 사항을 고려해야 합니다.

  • 쿼리 작성기 메서드에 전달된 매개 변수는 시퀀스에서 ObjectQuery의 후속 인스턴스에 의해 집계되며, Parameters 속성을 사용하여 액세스할 수 있습니다. 매개 변수를 추가한 다음 쿼리를 컴파일하거나 실행하지 않았으면 컬렉션에서 매개 변수를 제거할 수도 있고 컬렉션을 지울 수도 있습니다. 매개 변수 이름은 변경할 수 없지만 값은 언제든지 변경할 수 있습니다.

  • 매개 변수는 ObjectParameterCollection에서 고유해야 합니다. 컬렉션에 같은 이름의 매개 변수가 두 개 있을 수 없습니다.

  • Union, UnionAll, Intersect, Except 등의 구성 메서드를 사용할 때 매개 변수 컬렉션은 병합됩니다. 매개 변수 집합이 호환되지 않거나 불완전할 때 또는 두 쿼리의 매개 변수 컬렉션에 동일한 이름이 존재하면 예외가 throw됩니다.

참고 항목

개념

개념적 모델 쿼리(Entity Framework)
관련 개체 로드(Entity Framework)