LINQ-to-SQL Table.Attach 的作用是什么?
LINQ-to-SQL 方法 Table
和 Table
到底有什么作用,以及它们的示例/情况是什么正确使用?
另外,请查看此相关问题:如何将 LINQ-to-SQL 数据对象与 DataContext 的跟踪机制分离?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它在将数据序列化/反序列化到其他层的多层应用程序中非常有用。
简短版本:
Attach()
告诉 DataContext 该实体不是新的(对于 插入),而是一个更新的实体,意味着 在数据库中更新。长版本:
您有一个DataContext,您的实体存在于其中。新实体被插入,现有实体被更新。现在您需要将一些实体发送到另一层,DataContext 然后分离所述实体并将其发送走。
在另一层,实体被修改并发送回数据层。现在,拥有您的实体的前 DataContext 可能不再存在(例如,如果它是无状态的)或者不知道您的反序列化实体,那么您该怎么办?您创建一个新的 DataContext 或使用现有的 DataContext 并使用
Attach()
方法 - 这样 DataContext 就知道实体应该是更新并且不应插入到数据库中。对于
AttachAll()
也是如此,但对于多个实体。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.LINQ to SQL 维护 DataContext 对象中实体的状态。从数据库加载的实体与 DataContext 相关联,DataContext 负责跟踪对实体的任何更改,以便在保存实体时对数据库进行适当的更改。
实体在序列化时可以与 DataContext 分离(例如在 n 层应用程序中传递给客户端)。当客户端将实体返回到 DA 层时,您需要将其重新附加到 DataContext,然后才能在数据库中更新或删除它。 Attach 方法执行此操作。
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.