EntityCollection<TEntity>.Load(MergeOption) 方法

定义

使用指定的合并选项将相关对象加载到集合中。

public:
 override void Load(System::Data::Objects::MergeOption mergeOption);
public override void Load (System.Data.Objects.MergeOption mergeOption);
override this.Load : System.Data.Objects.MergeOption -> unit
Public Overrides Sub Load (mergeOption As MergeOption)

参数

mergeOption
MergeOption

指定此集合中的对象应如何与从以前针对相同 ObjectContext 的查询中返回的对象合并。

示例

此示例基于 Adventure Works 销售模型。 若要运行此示例中的代码,必须已将 AdventureWorks 销售模型添加到您的项目中,并将项目配置为使用实体框架。 为此,请完成 如何:手动配置实体框架项目如何:手动定义模型和映射文件中的过程。

本示例为 SalesOrderHeader 实体加载相关 Contact 对象。

// Specify the customer ID.
int contactID = 4332;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    context.ContextOptions.LazyLoadingEnabled = false;

    // Get a specified customer by contact ID.
    var contact =
        (from c in context.Contacts
         where c.ContactID == contactID
         select c).First();

    // Load the orders for the customer explicitly.
    if (!contact.SalesOrderHeaders.IsLoaded)
    {
        contact.SalesOrderHeaders.Load();
    }

    foreach (SalesOrderHeader order in contact.SalesOrderHeaders)
    {
        // Load the items for the order if not already loaded.
        if (!order.SalesOrderDetails.IsLoaded)
        {
            order.SalesOrderDetails.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.SalesOrderDetails)
        {
            Console.WriteLine(String.Format("Product: {0} "
                + "Quantity: {1}", item.ProductID.ToString(),
                item.OrderQty.ToString()));
        }
    }
}

注解

此方法在加载集合之前调用内部 RelatedEnd.ValidateLoad 方法,这将验证对 Load 的调用是否具有正确的条件。 方法 RelatedEnd.ValidateLoad 检查:

当集合中的对象已加载到 时 ObjectContextLoad 方法将强制由 MergeOptionmergeOption 参数指定的 。 有关详细信息,请参阅标识解析、状态管理和更改跟踪

若要显式加载相关对象,必须在导航属性返回的相关端调用 Load 方法。 对于一对多关系,请在 上EntityCollection<TEntity>调用 Load 方法。 对于一对一关系,请在 上EntityReference<TEntity>调用 Load 。 这样可将相关对象数据加载到对象上下文中。 可以使用 Visual Basic) 中的循环 (For Each...Next 枚举返回的结果foreach集合,并有条件地调用Load结果中每个实体的 和 EntityReference<TEntity>EntityCollection<TEntity> 属性。

无论 是否为 true,方法Load都从数据源IsLoaded加载相关对象。

注意

当您在 Load (C#) 或 foreach (Visual Basic) 枚举过程中调用 For Each 方法时,对象服务会尝试打开一个新的数据读取器。 除非您已经通过在连接字符串中指定 multipleactiveresultsets=true 启用了多个活动结果集,否则此操作将失败。 还可以将查询的结果加载到一个 List<T> 集合中。 这样将关闭数据读取器,并允许您对集合进行枚举来加载引用的对象。

EntityCollection<TEntity>.Load 方法与 EntityReference<TEntity>.Load 方法同步。

适用于