Table<TEntity>.Attach Method

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Include Protected Members
Include Inherited Members

Include Silverlight Members
Include Silverlight for Windows Phone Members
Include XNA Framework Members

Attaches an entity to the DataContext.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

Overload List

  Name Description
Public methodSupported by Silverlight for Windows Phone Attach(TEntity) Attaches a disconnected or "detached" entity to a new DataContext when original values are required for optimistic concurrency checks.
Public methodSupported by Silverlight for Windows Phone Attach(TEntity, Boolean) Attaches an entity to the DataContext in either a modified or unmodified state.
Public methodSupported by Silverlight for Windows Phone Attach(TEntity, TEntity) Attaches an entity to the DataContext in either a modified or unmodified state by specifying both the entity and its original state.

Top

Remarks

Use the Attach methods with entities that have been created in one DataContext, serialized to a client, and then deserialized back (with the intention to perform an update or delete operation).

Do not try to Attach an entity that has not been detached through serialization. Entities that have not been serialized still maintain associations with deferred loaders that can cause unexpected results if the entity becomes tracked by a second data context.

When a new entity is attached, deferred loaders for any child collections (for example, EntitySet collections of entities from associated tables) are initialized. When SubmitChanges is called, members of the child collections are put into an Unmodified state. To update members of a child collection, you must explicitly call Attach and specify that entity.

Attach attaches all entities in the object graph of the provided object. For example, the following C# code:

using (SampleDataContext db = new SampleDataContext()) {
    Employee employee = new Employee { employeeId = 1 };

    Master master = new Master();
    master.Employee = employee;

    Child child = new Child();
    child.Employee = employee;

    db.Employees.Attach(employee);

    master.Child = child;

    db.Masters.InsertOnSubmit(master);

    db.SubmitChanges();
}

The equivalent Visual Basic code is:

Using db As New SampleDataContext()
    Dim employee As New Employee With { .employeeId = 1 }

    Dim master As New Master()
    master.Employee = employee

    Dim child As New Child()
    child.Employee = employee

    db.Employees.Attach(employee)

    master.Child = child

    db.Masters.InsertOnSubmit(master)

    db.SubmitChanges()

End Using

Calling Attach on Employee attaches employee, master, and child, because the Employee has relationships to both master and child. You must explicitly call InsertOnSubmit to change the state from attached to inserted.