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 销售模型添加到项目中,并将项目配置为使用 Entity Framework。 为此,请完成 如何:手动配置 Entity Framework Project如何:手动定义模型和映射文件

此示例加载实体的相关 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 检查是否:

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

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

该方法 Load 从数据源加载相关对象(无论是否 IsLoadedtrue)。

注释

在 (C#) 或 Load (Visual Basic) 枚举期间foreach调用For Each该方法时,Object Services 会尝试打开新的数据读取器。 除非已在连接字符串中指定 multipleactiveresultsets=true 启用了多个活动结果集,否则此操作将失败。 还可以将查询结果加载到 List<T> 集合中。 这会关闭数据读取器,并使你能够枚举集合以加载引用的对象。

该方法 EntityCollection<TEntity>.LoadEntityReference<TEntity>.Load 该方法同步。

适用于