如何:显式加载相关对象(实体框架)

本主题提供有关如何显式加载相关对象的示例。第一个示例显式加载一位客户的所有订单和项。第二个示例使用单独的查询只加载包含相关项的选定订单。然后将这些订单附加到该客户。

本主题中的示例基于 Adventure Works 销售模型。若要运行本主题中的代码,必须已将 AdventureWorks 销售模型添加到您的项目中,并将项目配置为使用 实体框架。为此,请完成如何:手动配置实体框架项目如何:手动定义实体数据模型(实体框架) 中的过程。也可以使用实体数据模型向导定义 AdventureWorks 销售模型。有关更多信息,请参见如何:使用实体数据模型向导(实体框架)

示例

下面的示例加载属于单个 ContactSalesOrderHeader 对象,然后循环访问 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());
    }
}

下面的示例使用 EntityCollectionCreateSourceQuery 方法,只加载五个 SalesOrderHeader 对象,以及属于单个 Contact 的相关 SalesOrderDetail 对象。然后将此查询结果附加到原始 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());
    }
}

另请参见

任务

如何:执行返回实体类型的查询(实体框架)
如何:使用查询路径调整结果(实体框架)
如何:使用导航属性导航关系(实体框架)

概念

形成查询结果(实体框架)