locked
How to Clone a Entity Object RRS feed

  • Question

  • Hi guys,

    I'm doing a projet using the Silverlight Business Template (with WCF Ria Services).

    I need to implemente a method to clone an object.

    EX:

    public void Clone()
    {
      DbDomainContect context = new DbDomainContect();
    
      context.Load(context.GetEmployeeById(1), 
        (loadOpe) =>
          {
            if(!loadOpe.HasError) 
            {
               Employee emp = LoadOpe.Entities.FirstOrDefault();
               if(emp != null)
               {
                 // Now i need to clone the "emp" object and change the Name for exemple and save to the Database again
                 
                 // Clone and Save
                 Employee empClone = // Clone ?
                 empClone.Name = "New Name";   
    
                 context.SubmitChanges();
               }  
            }
          }, null);
    }

    How can i do that?

    Thursday, May 12, 2011 8:41 AM

Answers

  • i *think* something like this will work.  i don't have a compiler handy to verify.

    in your employee class, create a new method that returns the results of this.MemberwiseClone().  MemberwiseClone is a protected method of Object, so you won't just be able to call it on an employee object.  Hence the need to expose it through this Clone method:

    public Employee Clone()
    {
        return (Employee)this.MemberwiseClone();
    }

    then you can do:

    var empClone = emp.Clone();
    empClone.Name = "New Name";
    ...

    Thursday, May 12, 2011 8:48 AM

All replies

  • i *think* something like this will work.  i don't have a compiler handy to verify.

    in your employee class, create a new method that returns the results of this.MemberwiseClone().  MemberwiseClone is a protected method of Object, so you won't just be able to call it on an employee object.  Hence the need to expose it through this Clone method:

    public Employee Clone()
    {
        return (Employee)this.MemberwiseClone();
    }

    then you can do:

    var empClone = emp.Clone();
    empClone.Name = "New Name";
    ...

    Thursday, May 12, 2011 8:48 AM
  • thx guys for the fast reply, both solution worked

    Thursday, May 12, 2011 9:06 AM