通过


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调用该方法后,系统将不再保留指向此对象的引用,并且可以由垃圾回收器收集。

注释

仅当用户代码没有对分离对象的任何引用时,才能进行垃圾回收。

分离对象时,以下注意事项适用:

  • Detach 仅影响传递给方法的特定对象。 如果分离的对象在对象上下文中具有相关对象,则不会分离这些对象。

  • 分离对象不会影响数据源中的数据。

  • 在分离操作期间,不会强制实施级联删除指令和引用约束。

适用于

另请参阅