如何:显式加载 POCO 实体(实体框架)
本主题中的示例演示如何使用 ObjectContext 的 LoadProperty 方法显式加载相关对象。 有关使用延迟加载访问相关对象的示例,请参见如何:使用延迟加载来加载相关对象(实体框架)。 LoadProperty 方法可用于 POCO 实体和从 EntityObject 派生的实体。
本主题中的示例使用在如何:定义 POCO 实体(实体框架)中定义的 POCO 数据类、在如何:定义自定义对象上下文(实体框架)中创建的 AdventureWorksEntities 类(派生自 ObjectContext)以及在如何:自定义建模和映射文件以使用自定义对象(实体框架)中定义的基于 AdventureWorks 的数据模型。
示例
此示例返回前五个 Order
对象并调用 LoadProperty 方法以显式加载每个 Order
的相关 LineItem
对象。
Using context As New POCOAdventureWorksEntities()
Try
' Disable lazy loading.
context.ContextOptions.LazyLoadingEnabled = False
' Get the first five orders.
For Each order As Order In context.Orders.Take(5)
' Because LazyLoadingEnabled is set to false,
' we need to explicitly load the related line items for the order.
context.LoadProperty(order, "LineItems")
Console.WriteLine(String.Format("PO Number: {0}", order.ExtendedInfo.PurchaseOrderNumber))
Console.WriteLine(String.Format("Order Date: {0}", order.OrderDate.ToString()))
Console.WriteLine("Order items:")
For Each item As LineItem In order.LineItems
Console.WriteLine(String.Format("Product: {0} " & "Quantity: {1}", item.ProductID, item.OrderQty))
Next
Next
Catch ex As InvalidOperationException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
using (POCOAdventureWorksEntities context =
new POCOAdventureWorksEntities())
{
try
{
// Disable lazy loading.
context.ContextOptions.LazyLoadingEnabled = false;
// Get the first five orders.
foreach (Order order in context.Orders.Take(5))
{
// Because LazyLoadingEnabled is set to false,
// we need to explicitly load the related line items for the order.
context.LoadProperty(order, "LineItems");
Console.WriteLine(String.Format("PO Number: {0}",
order.ExtendedInfo.PurchaseOrderNumber));
Console.WriteLine(String.Format("Order Date: {0}",
order.OrderDate.ToString()));
Console.WriteLine("Order items:");
foreach (LineItem item in order.LineItems)
{
Console.WriteLine(String.Format("Product: {0} "
+ "Quantity: {1}", item.ProductID,
item.OrderQty));
}
}
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}