How do I duplicate an object?

二次信任 提交于 2019-12-25 17:25:30

问题


I have a plans list, or whatever it is, and I don't want any of them to be deleted. That's why when someone choose the "edit" option - I actually want to add a new plan with the same references, but just a new ID. Then, I don't care at all what changes will be made in it in the edit view (which is in fact the create view).

I use the same view whether it create new or edit, but the only difference is that if the action get a plan - I understand it is not create new but edit and then I want to display in the create view all the "edited" plan parameters, and if there isn't any plan (if the action does not get any plan) - I understand it's a totaly new plan (someone choose the "Create new" option), and then I want to display the same view - with blank fields.

Here is my code:

public ActionResult CreatePlan(Plan? plan)
        {
            if (plan == null)
            {
                return View();
            }
            else 
            {
                Plan oldPlan = db.PlanSet.Single(p => p.Id == plan.Value.Id);
                return View(oldPlan);
            }
        }

Currently, as you can see, if the action does get an object - it lets me edit the old plan.

How can I duplicate it so any change that will be made in the view - will be saved with another plan ID??? Hope I made myself clear and am happy to get some help !


回答1:


I think what you want is: Object.MemberwiseClone().

Object.MemberwiseClone() creates a shallow copy of an object, i.e. it creates a new object and copies the references from the old object (of course, value types are duplicated).

Now, since MemberwiseClone is actually protected, you have to do something like:

public class Plan 
{
    public Plan clone()
    {
        return (Plan)this.MemberwiseClone();
    }
}



回答2:


give your Plan class a copy constructor and instead of returning View(oldPlan) return View(Plan(oldPlan))




回答3:


For my question I didn't need to use something complicated at all.

All I needed to to is to create two get actions, one with blank fields and another with fields full with the edited object.

the two views send their parameters to the same post action, that gets the sent object and add it to the database. when I write: db.PlanSet.AddObject(plan); -it automatically adds the same object with new Id, without removing or changing the original object.

Good Luck!!



来源:https://stackoverflow.com/questions/8225985/how-do-i-duplicate-an-object

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