ObjectContext.Attach(IEntityWithKey) 方法

定义

在对象具有实体键时将对象或对象图附加到对象上下文。

public:
 void Attach(System::Data::Objects::DataClasses::IEntityWithKey ^ entity);
public void Attach (System.Data.Objects.DataClasses.IEntityWithKey entity);
member this.Attach : System.Data.Objects.DataClasses.IEntityWithKey -> unit
Public Sub Attach (entity As IEntityWithKey)

参数

entity
IEntityWithKey

要附加的对象。

例外

entitynull

无效的实体键。

示例

在此示例中,附加了两个对象,然后定义了关系。

private static void AttachRelatedObjects(
    ObjectContext currentContext,
    SalesOrderHeader detachedOrder,
    List<SalesOrderDetail> detachedItems)
{
    // Attach the root detachedOrder object to the supplied context.
    currentContext.Attach(detachedOrder);

    // Attach each detachedItem to the context, and define each relationship
    // by attaching the attached SalesOrderDetail object to the EntityCollection on
    // the SalesOrderDetail navigation property of the now attached detachedOrder.
    foreach (SalesOrderDetail item in detachedItems)
    {
        currentContext.Attach(item);
        detachedOrder.SalesOrderDetails.Attach(item);
    }
}

注解

调用 AttachObjectContext 可将对象附加到对象上下文。 当对象已存在于数据源中但当前尚未附加到上下文时采用此方法。 有关详细信息,请参阅 自定义对象

Attach 用于在对象图中附加对象或顶级对象。

要附加的对象必须实现 IEntityWithKey 以公开 EntityKey。 所有生成的实体类都实现 IEntityWithKey

附加相关对象时,还必须调用 AttachEntityReference<TEntity>EntityCollection<TEntity> 来定义关系。

此方法调用 AttachTo 方法。

在附加对象时需要考虑下列注意事项:

  • 如果要附加的对象具有相关对象,则这些对象也会附加到对象上下文。

  • 对象以未更改状态添加到对象上下文。

  • 传递到 Attach 方法的对象必须具有有效的 EntityKey 值。 如果对象没有有效的 EntityKey 值,请使用 AttachTo 方法指定实体集的名称。

适用于

另请参阅