克隆 EF 4.0 中的自我跟踪实体?

发布于 2024-12-20 00:27:06 字数 40 浏览 1 评论 0原文

如何在 EF 4.0 中克隆自我跟踪实体图?

谢谢

How I can clone a Self-Tracking Entity Graph in EF 4.0?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

极致的悲 2024-12-27 00:27:06

自跟踪实体是可序列化的,因此获得实体深度克隆(深度克隆 = 图形克隆)的最简单方法是使用 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.

暗恋未遂 2024-12-27 00:27:06

当您说“克隆”时,您的意思是创建一个将持久存在的新实体,还是只是创建另一个作为同一实体的内存副本的“临时”实体?

如果您想在内存中进行复制,您始终可以创建实体类的新实例,并复制字段。对它的更改不会被跟踪,因为您还没有告诉它的上下文。

var newInstance = new SomeEntity() { SomeProperty = oldInstance.SomeProperty };

如果您想创建一个将被持久化的新实体,那么只需执行插入新记录所需的常规操作即可。例如:从

context.SomeEntities.Add(newInstance);

逻辑上讲,您无法创建跟踪更改的完整副本,而是引用同一实例。您会选择该对象的哪个版本?

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.

var newInstance = new SomeEntity() { SomeProperty = oldInstance.SomeProperty };

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.:

context.SomeEntities.Add(newInstance);

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文