Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does LINQ-to-SQL Table<T>.Attach do?

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?

like image 212
smartcaveman Avatar asked Mar 09 '11 10:03

smartcaveman


2 Answers

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.

like image 59
Jaroslav Jandek Avatar answered Oct 04 '22 02:10

Jaroslav Jandek


LINQ to SQL maintains the state of entities in a DataContext object. Entities that are loaded from the database are associated with a DataContext that is responsible for tracking any changes to the entity so when you save it the appropriate changes are made to the database.

Entities can become detached from the DataContext when they are serialized (for passing to a client for example in an n-tier application). When the client returns the entity back to your DA layer you will need to reattach it to a DataContext before it can be updated or deleted in the database. The Attach method performs this operation.

like image 33
Simon P Stevens Avatar answered Oct 04 '22 02:10

Simon P Stevens