Clone (deep copy) Entity LINQ

I would like to deeply copy Entity, and I am looking for the best way to do this. I am also concerned about the performances.

I plan to have all of my objects implementing ICloneable, where Clone () will be basically a shadow copy and clone all the links.

For example:

[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 this a good way to do this? Or should I load the object using linq, delete all primary keys (set id to 0), and then use the Create (entity) function to duplicate it? Could reflection be the right solution (not too slow)? At least reflection can avoid the problem of updating my entity class (e.g. new members) without updating the Clone function ...

+3
source share
2

ICloneable - ; , . , , . , . , , , , . , , .

0

:

    private static object CloneObject(object obj)
    {
        Type cloneType = obj.GetType();

        object clone = Activator.CreateInstance(cloneType);

        PropertyInfo[] properties = cloneType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty);
        foreach (PropertyInfo property in properties)
        {
            if (property.CanWrite)
            {
                object value = property.GetValue(obj, null);
                property.SetValue(clone, value, null);
            }
        }

        return clone;
    }

Entity newEnt = new Entity();
newEnt = (Entity)CloneObject(oldEnt);
0

Source: https://habr.com/ru/post/1718401/


All Articles