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

只谈情不闲聊 提交于 2019-11-30 22:45:44

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5244096/what-does-linq-to-sql-tablet-attach-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!