방법: 익명 형식을 반환하는 쿼리 실행(Entity Framework)

이 항목에서는 컬렉션, 행 및 참조와 같은 익명 형식의 인스턴스 컬렉션을 반환하는 쿼리를 실행하는 방법에 대한 예제를 제공합니다. 이러한 예제의 쿼리 결과는 행 형식의 컬렉션입니다. 자세한 내용은 형식 시스템(Entity SQL)을 참조하십시오. 다음의 엔터티 프레임워크 쿼리 기술을 각각 사용하여 동일한 예제를 보여 줍니다.

  • LINQ to Entities

  • ObjectQuery<T>를 사용한 Entity SQL

  • ObjectQuery<T>의 쿼리 작성기 메서드

이 항목의 예제는 Adventure Works Sales 모델을 기반으로 합니다. 이 예제의 코드를 실행하려면 프로젝트에 AdventureWorks Sales 모델을 추가하고 Entity Framework를 사용하도록 프로젝트를 구성해야 합니다. 이렇게 하려면 방법: Entity Framework 프로젝트 수동 구성방법: 엔터티 데이터 모델 수동 정의(Entity Framework)의 절차를 수행합니다. 엔터티 데이터 모델 마법사를 사용하여 AdventureWorks Sales 모델을 정의할 수도 있습니다. 자세한 내용은 방법: 엔터티 데이터 모델 마법사 사용(Entity Framework)을 참조하십시오.

예제

다음은 LINQ to Entities 예제입니다.

Using AWEntities As New AdventureWorksEntities
    Dim products As ObjectQuery(Of Product) = AWEntities.Product

    Dim query = _
        From product In products _
        Select New With _
        { _
            .ProductId = product.ProductID, _
            .ProductName = product.Name _
        }

    Console.WriteLine("Product Info:")
    For Each productInfo In query
        Console.WriteLine("Product Id: {0} Product name: {1} ", _
                productInfo.ProductId, productInfo.ProductName)
    Next
End Using
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectQuery<Product> products = AWEntities.Product;
    var query =
        from product in products
        select new
        {
            ProductId = product.ProductID,
            ProductName = product.Name
        };

    Console.WriteLine("Product Info:");
    foreach (var productInfo in query)
    {
        Console.WriteLine("Product Id: {0} Product name: {1} ",
            productInfo.ProductId, productInfo.ProductName);
    }
}

다음은 Entity SQL 예제입니다.

Using advWorksContext As AdventureWorksEntities = New AdventureWorksEntities
    Dim commandText As String = "SELECT p.ProductID, p.Name FROM " & _
        "AdventureWorksEntities.Product as p"

    Try
        Dim query As New ObjectQuery(Of DbDataRecord)(commandText, advWorksContext)

        For Each result As DbDataRecord In query
            Console.WriteLine("ID {0} Name {1}", result.Item(0), result.Item(1))
        Next
    Catch ex As EntityException
        Console.WriteLine(ex.ToString())
    Catch ex As InvalidOperationException
        Console.WriteLine(ex.ToString())
    End Try
End Using
using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
{
    string myQuery = @"SELECT p.ProductID, p.Name FROM 
        AdventureWorksEntities.Product as p";
    try
    {
        foreach (DbDataRecord rec in
            new ObjectQuery<DbDataRecord>(myQuery, advWorksContext))
        {
            Console.WriteLine("ID {0}; Name {1}", rec[0], rec[1]);
        }
    }
    catch (EntityException ex)
    {
        Console.WriteLine(ex.ToString());
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

다음은 쿼리 작성기 방법을 사용한 예제입니다.

Using advWorksContext As AdventureWorksEntities = _
    New AdventureWorksEntities

    Try
        ' Use the Select method to define the projection.
        Dim query As ObjectQuery(Of DbDataRecord) = _
            advWorksContext.Product.Select("it.ProductID, it.Name")

        ' Iterate through the collection of data rows.
        For Each result As DbDataRecord In query
            Console.WriteLine("ID{0}: Name {1}", _
                              result.Item(0), result.Item(1))
        Next

    Catch ex As EntitySqlException
        Console.WriteLine(ex.ToString())
    End Try
End Using
using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
{
    try
    {
        // Use the Select method to define the projection.
        ObjectQuery<DbDataRecord> query =
            advWorksContext.Product.Select("it.ProductID, it.Name");

        // Iterate through the collection of data rows.
        foreach (DbDataRecord rec in query)
        {
            Console.WriteLine("ID {0}; Name {1}", rec[0], rec[1]);
        }
    }
    catch (EntitySqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

참고 항목

작업

방법: 엔터티 형식을 반환하는 쿼리 실행(Entity Framework)
방법: 기본 형식을 반환하는 쿼리 실행(Entity Framework)
방법: 매개 변수가 있는 쿼리 실행(Entity Framework)

개념

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

기타 리소스

엔터티 데이터 모델 쿼리(Entity Framework 작업)