다음을 통해 공유


방법: 탐색 속성을 사용하여 관계 탐색(Entity Framework)

이 항목에서는 탐색 속성을 통해 관계를 탐색하는 방법을 보여 줍니다. 자세한 내용은 탐색 속성을 참조하십시오. 예제에서는 성이 "Zhou"인 연락처의 모든 주문을 가져옵니다. Contact.SalesOrderHeader 탐색 속성을 사용하여 각 연락처의 SalesOrderHeader 개체 컬렉션을 가져옵니다. 다음의 Entity Framework 쿼리 기술을 각각 사용하여 동일한 예제를 보여 줍니다.

  • LINQ to Entities

  • ObjectQuery<T>가 포함된 Entity SQL

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

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

예제

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

Dim lastName = "Zhou"
Using context As New AdventureWorksEntities
    Dim contacts As ObjectSet(Of Contact) = context.Contacts

    Dim ordersQuery = From contact In contacts _
        Where contact.LastName = lastName _
        Select New With _
                {.LastName = contact.LastName, _
                 .Orders = contact.SalesOrderHeaders}

    For Each order In ordersQuery
        Console.WriteLine("Name: {0}", order.LastName)
        For Each orderInfo In order.Orders

            Console.WriteLine("Order ID: {0}, Order date: {1}, Total Due: {2}", _
                    orderInfo.SalesOrderID, orderInfo.OrderDate, orderInfo.TotalDue)
        Next

        Console.WriteLine("")
    Next
End Using
string lastName = "Zhou";
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    ObjectSet<Contact> contacts = context.Contacts;

    var ordersQuery = from contact in contacts
                      where contact.LastName == lastName
                      select new { LastName = contact.LastName, Orders = contact.SalesOrderHeaders };

    foreach (var order in ordersQuery)
    {
        Console.WriteLine("Name: {0}", order.LastName);
        foreach (SalesOrderHeader orderInfo in order.Orders)
        {
            Console.WriteLine("Order ID: {0}, Order date: {1}, Total Due: {2}",
                orderInfo.SalesOrderID, orderInfo.OrderDate, orderInfo.TotalDue);
        }
        Console.WriteLine("");
    }
}

다음은 Entity SQL 예제입니다.

Using context As New AdventureWorksEntities()
    Dim esqlQuery As String = "SELECT c.FirstName, c.SalesOrderHeaders " & _
        " FROM AdventureWorksEntities.Contacts AS c where c.LastName = @ln"

    Dim query As New ObjectQuery(Of DbDataRecord)(esqlQuery, context)

    ' Add parameters to the collection. 
    query.Parameters.Add(New ObjectParameter("ln", "Zhou"))

    For Each rec As DbDataRecord In query

        ' Display contact's first name. 
        Console.WriteLine("First Name {0}: ", rec(0))
        Dim list As List(Of SalesOrderHeader) = TryCast(rec(1), List(Of SalesOrderHeader))
        ' Display SalesOrderHeader information 
        ' associated with the contact. 
        For Each soh As SalesOrderHeader In list
            Console.WriteLine(" Order ID: {0}, Order date: {1}, Total Due: {2}",
                              soh.SalesOrderID, soh.OrderDate, soh.TotalDue)
        Next
    Next
End Using
using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    string esqlQuery = @"SELECT c.FirstName, c.SalesOrderHeaders 
        FROM AdventureWorksEntities.Contacts AS c where c.LastName = @ln";
    ObjectQuery<DbDataRecord> query = new ObjectQuery<DbDataRecord>(esqlQuery, context);
    query.Parameters.Add(new ObjectParameter("ln", "Zhou"));

    foreach (DbDataRecord rec in query)
    {

        // Display contact's first name.
        Console.WriteLine("First Name {0}: ", rec[0]);
        List<SalesOrderHeader> list = rec[1] as List<SalesOrderHeader>;
        // Display SalesOrderHeader information 
        // associated with the contact.
        foreach (SalesOrderHeader soh in list)
        {
            Console.WriteLine("   Order ID: {0}, Order date: {1}, Total Due: {2}",
                soh.SalesOrderID, soh.OrderDate, soh.TotalDue);
        }
    }
}

다음은 쿼리 작성기 메서드 예제입니다.

Dim lastName = "Zhou"

Using context As New AdventureWorksEntities()
    ' 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))

    For Each rec As DbDataRecord In query.Execute(MergeOption.AppendOnly)

        ' Display contact's first name. 
        Console.WriteLine("First Name {0}: ", rec(0))
        Dim list As List(Of SalesOrderHeader) = TryCast(rec(2), List(Of SalesOrderHeader))
        ' Display SalesOrderHeader information 
        ' associated with the contact. 
        For Each soh As SalesOrderHeader In list
            Console.WriteLine(" Order ID: {0}, Order date: {1}, Total Due: {2}", _
                              soh.SalesOrderID, soh.OrderDate, soh.TotalDue)
        Next
    Next
End Using
string lastName = "Zhou";
using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    // 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));

    foreach (DbDataRecord rec in
        query.Execute(MergeOption.AppendOnly))
    {

        // Display contact's first name.
        Console.WriteLine("First Name {0}: ", rec[0]);
        List<SalesOrderHeader> list = rec[2]
            as List<SalesOrderHeader>;
        // Display SalesOrderHeader information 
        // associated with the contact.
        foreach (SalesOrderHeader soh in list)
        {
            Console.WriteLine("   Order ID: {0}, " +
                "Order date: {1}, Total Due: {2}",
                soh.SalesOrderID, soh.OrderDate, soh.TotalDue);
        }
    }
}

참고 항목

작업

방법: 쿼리 경로를 사용하여 결과 셰이핑(Entity Framework)

개념

개념적 모델 쿼리(Entity Framework)
관계 정의 및 관리(Entity Framework)