Duplicating a model that has a hierarchy

前端 未结 2 1496
礼貌的吻别
礼貌的吻别 2020-12-22 09:13

My model looks something like this:

Company
-Locations

Locations
-Stores

Stores
-Products

So I want to make a copy of a Company, and all

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-22 09:24

    I would add a method to each model that needs to be cloneable this way, I'd recommend an interface for it also.

    It could be done something like this:

    //Company.cs
    Company DeepClone()
    {
        Company clone = new Company();
    
        clone.Name = this.name;
        //...more properties (be careful when copying reference types)
    
        clone.Locations = new List(this.Locations.Select(l => l.DeepClone()));
    
        return clone;
    }
    

    You should repeat this basic pattern for every class and "child" class that needs to be copiable. This way each object is aware of how to create a deep clone of its self, and passes responsibility for child objects off to the child class, neatly encapsulating everything.

    It could be used this way:

    Company copyOfCompany123 = DbContext.Companies.Find(123).DeepClone;
    

    My apologies if there are any errors in the above code; I don't have Visual Studio available at the moment to verify everything, I'm working from memory.


    One other really simple and code efficient way to deeply clone an object using serialization can be found in this post How do you do a deep copy an object in .Net (C# specifically)?

    public static T DeepClone(T obj)
    {
     using (var ms = new MemoryStream())
     {
       var formatter = new BinaryFormatter();
       formatter.Serialize(ms, obj);
       ms.Position = 0;
    
       return (T) formatter.Deserialize(ms);
     }
    }
    

    Just be aware that this can have some pretty serious resource and performance issues depending on your object structure. Every class that you want to use it on must also be marked with the [Serializable] attribute.

提交回复
热议问题