How to: Explicitly Load POCO Entities
The examples in this topic show you how to explicitly load related objects by using the LoadProperty method on the ObjectContext. For an example of using lazy loading to access related objects, see How to: Use Lazy Loading to Load Related Objects. The LoadProperty method can be used with POCO entities and with entities that derive from EntityObject.
The examples in this topic use the POCO data classes that are defined in How to: Define POCO Entities, the AdventureWorksEntities class (derived from ObjectContext) that is created in How to: Define a Custom Object Context, and an AdventureWorks-based data model that is defined in How to: Customize Modeling and Mapping Files to Work with Custom Objects.
Example
This example returns the first five Order
objects and calls the LoadProperty method to explicitly load the related LineItem
objects for each Order
.
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);
}
}
See Also
Concepts
Loading Related POCO Entities
Customizing Objects
Working with POCO Entities