克隆 EF 4.0 中的自我跟踪实体?
如何在 EF 4.0 中克隆自我跟踪实体图?
谢谢
How I can clone a Self-Tracking Entity Graph in EF 4.0?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何在 EF 4.0 中克隆自我跟踪实体图?
谢谢
How I can clone a Self-Tracking Entity Graph in EF 4.0?
Thanks
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(2)
自跟踪实体是可序列化的,因此获得实体深度克隆(深度克隆 = 图形克隆)的最简单方法是使用 DataContractSerializer 对其进行序列化并立即反序列化。反序列化的实体将是您的图表的克隆。
Self tracking entities are serializable so the simplest way to get deep clone of the entity (deep clone = clone of the graph) is to use
DataContractSerializer
and serialize and immediately deserialize it. Deserialized entity will be your clone of the graph.当您说“克隆”时,您的意思是创建一个将持久存在的新实体,还是只是创建另一个作为同一实体的内存副本的“临时”实体?
如果您想在内存中进行复制,您始终可以创建实体类的新实例,并复制字段。对它的更改不会被跟踪,因为您还没有告诉它的上下文。
如果您想创建一个将被持久化的新实体,那么只需执行插入新记录所需的常规操作即可。例如:从
逻辑上讲,您无法创建跟踪更改的完整副本,而是引用同一实例。您会选择该对象的哪个版本?
When you say "clone", do you mean to create a new entity that will be persisted, or to just create another "transient" entity that is an in-memory copy of the same entity?
If you want to make an in-memory copy, you can always create a new instance of the entity class, and copy over the fields. Changes to it won't be tracked, since you haven't told the context about it.
If you want to create a new entity that will be persisted, then simply do the normal operations you'd do to insert a new record. E.g.:
You can't logically make a full copy that tracks changes, but refers to the same instance. Which version of the object would you take?