问题
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