방법: 명시적으로 관련 개체 로드(Entity Framework)
이 항목에서는 관련 개체를 명시적으로 로드하는 방법에 대한 예제를 제공합니다. 첫 번째 예제는 단일 컴퓨터에 대해 모든 주문과 항목을 명시적으로 로드합니다. 두 번째 예제는 별도의 쿼리를 사용하여 관련 항목이 있는 선택한 주문만 로드합니다. 이러한 주문은 고객에 연결됩니다.
이 항목의 예제는 Adventure Works Sales 모델을 기반으로 합니다. 이 항목의 코드를 실행하려면 프로젝트에 AdventureWorks Sales 모델을 추가하고 프로젝트에서 엔터티 프레임워크를 사용하도록 구성해야 합니다. 이렇게 하려면 방법: Entity Framework 프로젝트 수동 구성 및 방법: 엔터티 데이터 모델 수동 정의(Entity Framework)의 절차를 수행합니다. 엔터티 데이터 모델 마법사를 사용하여 AdventureWorks Sales 모델을 정의할 수도 있습니다. 자세한 내용은 방법: 엔터티 데이터 모델 마법사 사용(Entity Framework)을 참조하십시오.
예제
다음 예제에서는 단일 Contact에 속하는 SalesOrderHeader 개체를 로드한 다음 EntityCollection의 SalesOrderHeader 개체를 반복합니다. 컬렉션의 각 SalesOrderHeader 개체에서 Load 메서드는 데이터베이스에서 관련 SalesOrderDetail 개체의 컬렉션을 검색하기 위해 호출됩니다.
' Specify the customer ID.
Dim customerId As Integer = 4332
Using context As New AdventureWorksEntities
Try
' Get a specified customer by contact ID.
Dim customer As Contact = context.Contact _
.Where("it.ContactID = @customerId", _
New ObjectParameter("customerId", customerId)).First()
' Load the orders for the customer
If (Not customer.SalesOrderHeader.IsLoaded) Then
customer.SalesOrderHeader.Load()
End If
For Each order As SalesOrderHeader In customer.SalesOrderHeader
' Load the items for the order if not already loaded.
If Not order.SalesOrderDetail.IsLoaded Then
order.SalesOrderDetail.Load()
End If
Console.WriteLine(String.Format("PO Number: {0}", _
order.PurchaseOrderNumber))
Console.WriteLine(String.Format("Order Date: {0}", _
order.OrderDate.ToString()))
Console.WriteLine("Order items:")
Dim item As SalesOrderDetail
For Each item In order.SalesOrderDetail
Console.WriteLine(String.Format("Product:{0}" _
+ "Quantity: {1}", item.ProductID.ToString(), _
item.OrderQty.ToString()))
Next
Next
Catch ex As EntitySqlException
Console.WriteLine(ex.ToString())
Catch ex As EntityCommandExecutionException
Console.WriteLine(ex.ToString())
End Try
End Using
// Specify the customer ID.
int customerId = 4332;
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
try
{
// Get a specified customer by contact ID.
Contact customer = context.Contact
.Where("it.ContactID = @customerId",
new ObjectParameter("customerId", customerId)).First();
// Load the orders for the customer
if (!customer.SalesOrderHeader.IsLoaded)
{
customer.SalesOrderHeader.Load();
}
foreach (SalesOrderHeader order in customer.SalesOrderHeader)
{
// Load the items for the order if not already loaded.
if (!order.SalesOrderDetail.IsLoaded)
{
order.SalesOrderDetail.Load();
}
Console.WriteLine(String.Format("PO Number: {0}",
order.PurchaseOrderNumber));
Console.WriteLine(String.Format("Order Date: {0}",
order.OrderDate.ToString()));
Console.WriteLine("Order items:");
foreach (SalesOrderDetail item in order.SalesOrderDetail)
{
Console.WriteLine(String.Format("Product: {0} "
+ "Quantity: {1}", item.ProductID.ToString(),
item.OrderQty.ToString()));
}
}
}
catch (EntitySqlException ex)
{
Console.WriteLine(ex.ToString());
}
catch (EntityCommandExecutionException ex)
{
Console.WriteLine(ex.ToString());
}
}
다음 예제에서는 EntityCollection의 CreateSourceQuery 메서드를 사용하여 단일 Contact에 속하며 관련된 SalesOrderDetail 개체가 있는 SalesOrderHeader 개체 5개만 로드합니다. 이 쿼리 결과는 원래 SalesOrderHeaderEntityCollection에 연결됩니다.
' Specify the customer ID.
Dim customerId As Integer = 4332
Using context As New AdventureWorksEntities
Try
' Get a specified customer by contact ID.
Dim customer As Contact = context.Contact _
.Where("it.ContactID = @customerId", _
New ObjectParameter("customerId", customerId)).First()
' Return the customer's first five orders with line items and
' attach them to the SalesOrderHeader collection.
customer.SalesOrderHeader.Attach( _
customer.SalesOrderHeader.CreateSourceQuery() _
.Include("SalesOrderDetail").Take(5))
For Each order As SalesOrderHeader In customer.SalesOrderHeader
Console.WriteLine(String.Format("PO Number: {0}", _
order.PurchaseOrderNumber))
Console.WriteLine(String.Format("Order Date: {0}", _
order.OrderDate.ToString()))
Console.WriteLine("Order items:")
For Each item As SalesOrderDetail In order.SalesOrderDetail
Console.WriteLine(String.Format("Product: {0} " _
+ "Quantity: {1}", item.ProductID.ToString(), _
item.OrderQty.ToString()))
Next
Next
Catch ex As EntitySqlException
Console.WriteLine(ex.ToString())
End Try
End Using
// Specify the customer ID.
int customerId = 4332;
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
try
{
// Get a specified customer by contact ID.
Contact customer = context.Contact
.Where("it.ContactID = @customerId",
new ObjectParameter("customerId", customerId)).First();
// Return the customer's first five orders with line items and
// attach them to the SalesOrderHeader collection.
customer.SalesOrderHeader.Attach(
customer.SalesOrderHeader.CreateSourceQuery()
.Include("SalesOrderDetail").Take(5));
foreach (SalesOrderHeader order in customer.SalesOrderHeader)
{
Console.WriteLine(String.Format("PO Number: {0}",
order.PurchaseOrderNumber));
Console.WriteLine(String.Format("Order Date: {0}",
order.OrderDate.ToString()));
Console.WriteLine("Order items:");
foreach (SalesOrderDetail item in order.SalesOrderDetail)
{
Console.WriteLine(String.Format("Product: {0} "
+ "Quantity: {1}", item.ProductID.ToString(),
item.OrderQty.ToString()));
}
}
}
catch (EntitySqlException ex)
{
Console.WriteLine(ex.ToString());
}
}
참고 항목
작업
방법: 엔터티 형식을 반환하는 쿼리 실행(Entity Framework)
방법: 쿼리 경로를 사용하여 결과 모양 결정(Entity Framework)
방법: 탐색 속성을 사용하여 관계 탐색(Entity Framework)