Clone Self-Tracking Entities in EF 4.0?

时光总嘲笑我的痴心妄想 提交于 2019-12-11 16:45:44

问题


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

Thanks


回答1:


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.




回答2:


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?



来源:https://stackoverflow.com/questions/8406359/clone-self-tracking-entities-in-ef-4-0

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