views:

818

answers:

1

Hi,

I would like to deep copy an Entity and I am looking for the best way to do it. I am also concerned about performances.

I plan to have all my entities implementing ICloneable where Clone() will basically shadow copy and Clone all references.

For instance:

[DataContract()]    
class MyEntity {
    public int id;  
    public string name;     
    public EntitySet<AnotherEntity> myOtherEntity;
}

MyEntity Clone() {
 Entity ent = new Entity(); 
 ent.name = this.name;
 ent.myOtherEntity = this.myOtherEntity.Clone();
 return ent;
}

Is it a good way of doing it? Or should I load the entity with linq, remove all primary keys (set id to 0) and then use a Create(entity) function to duplicate it? Could reflection be a valid solution too (not too slow)? At least reflection can avoid the issue when updating my entity class (new members for instance) without updating the Clone function...

Thanks, Xavier

A: 

ICloneable is not a bad solution; it was, after all, designed for this purpose. I'm not sure I'd want to write an implementation for every entity type, but you could work around this with a code generator. Be careful but circular references, however. But if you care about performance at all when you do this, you're probably doing it way too often. If performance is an issue here, I'd want to know what problem you're actually trying to solve.

Craig Stuntz
I guess writing a code generator for it could be a nice solution, at least more stable with other developer in the team.
With EF v4 you can use a custom T4 artifact generation template to do this as part of model generation.
Craig Stuntz
I will take a look at it. Thank you :)