通过


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);
    }
}

注解

ObjectContext调用Attach对象以将对象附加到对象上下文。 当对象已存在于数据源中但当前未附加到上下文时执行此操作。

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

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

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

此方法调用 AttachTo 该方法。

附加对象时,以下注意事项适用:

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

  • 对象将添加到处于未更改状态的对象上下文中。

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

适用于

另请参阅