C# – What does LINQ-to-SQL Table.Attach do

cdatacontextlinqlinq-to-sql

What exactly does the LINQ-to-SQL method Table<T>.Attach() and Table<T>.AttachAll() and what is an example/situation for their proper usage?

Also, please check out this related question: How to detach a LINQ-to-SQL data object from the DataContext's tracking mechanism?

Best Answer

It is really useful in multi-tier applications that serialize/deserialize data to other layers.

Short version:

Attach() tells DataContext the entity is not new (for insert) but an updated entity that is meant to be updated in the DB.

Long version:

You have a DataContext where your entities exist. New entities get inserted, existing ones get updated. Now you need to send some entity to another tier, DataContext then detaches said entity and sends it away.
On the other tier the entity gets modified and sent back to your data layer. Now the former DataContext that had your entity may not exist anymore (eg. if it is stateless) or does not know your deserialized entity so what do you do? You create a new DataContext or use the existing one and use the Attach() method - this way the DataContext knows the entity is meant to be updated and should not be inserted into the database.

The same goes for AttachAll() but for multiple entities.