ObjectContext.Detach(Object) 方法

定義

從物件內容中移除物件。

public:
 void Detach(System::Object ^ entity);
public void Detach(object entity);
member this.Detach : obj -> unit
Public Sub Detach (entity As Object)

參數

entity
Object

物件需分離。 只有 被 entity 移除;如果有相關物件被同一 ObjectStateManager物件追蹤,則不會自動分離。

例外狀況

entitynull

entity 與此 ObjectContext 無關聯(例如,是新創且尚未與任何上下文相關聯,或是透過其他上下文獲得,或已經分離)。

範例

// This method is called to detach SalesOrderHeader objects and
// related SalesOrderDetail objects from the supplied object
// context when no longer needed by the application.
// Once detached, the resources can be garbage collected.
private static void DetachOrders(ObjectContext context,
    SalesOrderHeader order)
{
    try
    {
        // Detach each item from the collection.
        while (order.SalesOrderDetails.Count > 0)
        {
            // Detach the first SalesOrderDetail in the collection.
            context.Detach(order.SalesOrderDetails.First());
        }

        // Detach the order.
        context.Detach(order);
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

備註

將物件 ObjectStateManager從 中移除。 這會關閉該物件的變更追蹤與身份解析。 如需詳細資訊,請參閱附加和移除物件

方法被呼叫後 Detach ,系統將不再保留指向該物件的參考,垃圾回收器可將其收集。

Note

垃圾回收只有在使用者程式碼中沒有任何分離物件的參考時才會發生。

分離物件時需考慮以下事項:

  • Detach 只影響傳遞給方法的特定物件。 如果被分離的物件在物件上下文中有相關物件,這些物件就不會被分離。

  • 分離物件不會影響資料來源中的資料。

  • 在分離操作期間,級聯刪除指令與參照約束不會被強制執行。

如需詳細資訊,請參閱附加和移除物件

適用於

另請參閱