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

이 항목에서는 기본 형식을 반환하는 쿼리를 실행하는 방법에 대한 예제를 제공합니다. 다음의 엔터티 프레임워크 쿼리 기술을 각각 사용하여 동일한 예제를 보여 줍니다.

  • 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 예제입니다.

Dim contactId As Integer = 377

Using advWorksContext As New AdventureWorksEntities
    Try
        'Select a value.
        Dim orders As ObjectQuery(Of SalesOrderHeader) _
            = advWorksContext.SalesOrderHeader

        Dim orderQuery = _
        From order In orders _
        Where order.Contact.ContactID = contactId _
        Select order.PurchaseOrderNumber.Length

        ' Iterate through the collection of values.
        For Each result In orderQuery
            Console.WriteLine("{0}", result)
        Next

        ' Use a nullable DateTime value because ShipDate can be null.
        Dim shipDateQuery As IQueryable(Of Date?) = _
        From order In orders _
        Where order.Contact.ContactID = contactId _
        Select order.ShipDate

        ' Iterate through the collection of values.
        For Each shipDate In shipDateQuery
            Dim shipDateMessage As String = "date not set"

            If Not shipDate = Nothing Then
                shipDateMessage = shipDate.ToString()
            End If
            Console.WriteLine("Ship Date: {0}.", shipDateMessage)
        Next
    Catch ex As EntitySqlException
        Console.WriteLine(ex.ToString())
    Catch ex As InvalidOperationException
        Console.WriteLine(ex.ToString())
    End Try
End Using
int contactId = 377;

using (AdventureWorksEntities advWorksContext 
    = new AdventureWorksEntities())
{
    try
    {
        // Select a value.
        ObjectQuery<SalesOrderHeader> orders 
            = advWorksContext.SalesOrderHeader;
        
        IQueryable<Int32> orderQuery = 
            from order in orders                   
            where order.Contact.ContactID == contactId 
            select order.PurchaseOrderNumber.Length;

        // Iterate through the collection of values.
        foreach (Int32 result in orderQuery)
        {
            Console.WriteLine("{0}", result);
        }
        
        // Use a nullable DateTime value because ShipDate can be null.
        IQueryable<DateTime?> shipDateQuery =
            from order in orders
            where order.Contact.ContactID == contactId
            select order.ShipDate;

        // Iterate through the collection of values.
        foreach (DateTime? shipDate in shipDateQuery)
        {
            string shipDateMessage = "date not set";

            if (shipDate != null)
            {
                shipDateMessage = shipDate.ToString();
            }
            Console.WriteLine("Ship Date: {0}.", shipDateMessage);
        }
    }
    catch (EntitySqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

다음은 Entity SQL 예제입니다.

Dim contactId As Integer = 377

Using advWorksContext As New AdventureWorksEntities 
    Dim orderQueryString As String = "SELECT VALUE Length(order.PurchaseOrderNumber) " & _
        "FROM AdventureWorksEntities.SalesOrderHeader AS order " & _
        "WHERE order.CustomerID = @contactId"
    Dim shipDateQueryString As String = "SELECT VALUE order.ShipDate " & _
        "FROM AdventureWorksEntities.SalesOrderHeader AS order " & _
        "WHERE order.CustomerID = @contactId"

    Try
        ' Use the SelectValue method to select a value.
        Dim orderQuery As ObjectQuery(Of Int32) = _
            New ObjectQuery(Of Int32)(orderQueryString, _
                advWorksContext, MergeOption.NoTracking)
        orderQuery.Parameters.Add( _
            New ObjectParameter("contactId", contactId))

        ' Iterate through the collection of values.
        For Each result In orderQuery
            Console.WriteLine("{0}", result)
        Next

        ' Use a nullable DateTime value because ShipDate can be null.
        Dim shipDateQuery As ObjectQuery(Of Nullable(Of Date)) = _
            New ObjectQuery(Of Nullable(Of Date))(shipDateQueryString, _
        advWorksContext, MergeOption.NoTracking)
        shipDateQuery.Parameters.Add( _
            New ObjectParameter("contactId", contactId))

        ' Iterate through the collection of values.
        For Each shipDate In shipDateQuery
            Dim shipDateMessage As String = "date not set"

            If Not shipDate = Nothing Then
                shipDateMessage = shipDate.ToString()
            End If
            Console.WriteLine("Ship Date: {0}.", shipDateMessage)
        Next
    Catch ex As EntityException
        Console.WriteLine(ex.ToString())
    Catch ex As InvalidOperationException
        Console.WriteLine(ex.ToString())
    End Try
End Using
int contactId = 377;

using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
{
    string orderQueryString = @"SELECT VALUE Length(order.PurchaseOrderNumber)
        FROM AdventureWorksEntities.SalesOrderHeader AS order
        WHERE order.CustomerID = @contactId";
    string shipDateQueryString = @"SELECT VALUE order.ShipDate
        FROM AdventureWorksEntities.SalesOrderHeader AS order
        WHERE order.CustomerID = @contactId";

    try
    {
        // Use the SelectValue method to select a value.
        ObjectQuery<Int32> orderQuery =
            new ObjectQuery<Int32>(orderQueryString, 
                advWorksContext, MergeOption.NoTracking);
        orderQuery.Parameters.Add(
            new ObjectParameter("contactId", contactId));

        // Iterate through the collection of values.
        foreach (Int32 result in orderQuery)
        {
            Console.WriteLine("{0}", result);
        }

        // Use a nullable DateTime value because ShipDate can be null.
        ObjectQuery<Nullable<DateTime>> shipDateQuery =
            new ObjectQuery<Nullable<DateTime>>(shipDateQueryString,
        advWorksContext, MergeOption.NoTracking);
        shipDateQuery.Parameters.Add(                    
            new ObjectParameter("contactId", contactId));

        // Iterate through the collection of values.
        foreach (Nullable<DateTime> shipDate in shipDateQuery)
        {
            string shipDateMessage = "date not set";

            if (shipDate != null)
            {
                shipDateMessage = shipDate.ToString();
            }
            Console.WriteLine("Ship Date: {0}.", shipDateMessage);
        }
    }
    catch (EntityException ex)
    {
        Console.WriteLine(ex.ToString());
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

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

Dim contactId As Integer = 377

Using advWorksContext As New AdventureWorksEntities
    Try
        ' Use the SelectValue method to select a value.
        Dim orderQuery As ObjectQuery(Of Int32) = _
        advWorksContext.SalesOrderHeader _
            .Where("it.CustomerID = @contactId", _
                New ObjectParameter("contactId", contactId)) _
            .SelectValue(Of Int32)("Length(it.PurchaseOrderNumber)")

        ' Iterate through the collection of values.
        For Each result In orderQuery
            Console.WriteLine("{0}", result)
        Next

        ' Use a nullable DateTime value because ShipDate can be null.
        Dim shipDateQuery As ObjectQuery(Of Nullable(Of Date)) = _
        advWorksContext.SalesOrderHeader _
            .Where("it.CustomerID = @contactId", _
                New ObjectParameter("contactId", contactId)) _
            .SelectValue(Of Nullable(Of Date))("it.ShipDate")

        ' Iterate through the collection of values.
        For Each shipDate In shipDateQuery
            Dim shipDateMessage As String = "date not set"
            If Not shipDate = Nothing Then
                shipDateMessage = shipDate.ToString()
            End If
            Console.WriteLine("Ship Date: {0}.", shipDateMessage)
        Next
    Catch ex As EntitySqlException
        Console.WriteLine(ex.ToString())
    Catch ex As InvalidOperationException
        Console.WriteLine(ex.ToString())
    End Try
End Using
int contactId = 377;

using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
{
    try
    {
        // Use the SelectValue method to select a value.
        ObjectQuery<Int32> orderQuery =
            advWorksContext.SalesOrderHeader 
            .Where("it.CustomerID = @contactId", 
            new ObjectParameter("contactId", contactId))
            .SelectValue<Int32>("Length(it.PurchaseOrderNumber)");

        // Iterate through the collection of values.
        foreach (Int32 result in orderQuery)
        {
            Console.WriteLine("{0}", result);
        }

        // Use a nullable DateTime value because ShipDate can be null.
        ObjectQuery<Nullable<DateTime>> shipDateQuery =
            advWorksContext.SalesOrderHeader
            .Where("it.CustomerID = @contactId",
                new ObjectParameter("contactId", contactId))
            .SelectValue<Nullable<DateTime>>("it.ShipDate");
        
        // Iterate through the collection of values.
        foreach (Nullable<DateTime> shipDate in shipDateQuery)
        {
            string shipDateMessage = "date not set";

            if (shipDate != null)
            {
                shipDateMessage = shipDate.ToString();
            }
            Console.WriteLine("Ship Date: {0}.", shipDateMessage);
        }
    }
    catch (EntitySqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

참고 항목

작업

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

개념

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

기타 리소스

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