Copy Rows with BusinessObject.Clone()

Copy Rows with BusinessObject.Clone()

Old forum URL: forums.lhotka.net/forums/t/3097.aspx


Sarosh posted on Tuesday, June 26, 2007

Hi!

What is the correct way to copy rows from a BusinessObject Collection into itself based on some condition?

e.g.

I have 10 rows in my ProjectList BO Collection and I want to add a new rows based on some condition but new rows should have their own new ID's. If I use clone then I cannot change the new row's ID as the ID is readonly so the effect is that these new rows don't get saved back into the DB.

Thanks

Sarosh

Project ItemNew;

foreach(Project Item in ProjectList)

{

   if (Item.Active) // Copy only rows which are Active

   {

     ItemNew = Project.NewProject();

      ItemNew = Item.Clone() // this creates a copy but it now has the current rows ID

      // How do I copy all values from Item into ItemNew except the ID

      // How do I specify that this is a new row

   }

}

ajj3085 replied on Wednesday, June 27, 2007

You're probably best creating a Duplicate method for your Item class.  Duplicate would use clone, but before return the result would reset the id number.

HTH

Sarosh replied on Wednesday, June 27, 2007

Hi!

Yes, I ended up doing that plus I had to call MarkNew() as well otherwise that new row would not be added back to DB during a Save().

Sarosh

JoeFallon1 replied on Wednesday, June 27, 2007

I do something like this in a couple of places.

Private Sub DuplicateBO(ByVal source As BO)

Dim newBO As BO = BO.NewBO

newBO.Field1 = source.Field1
newBO.Field2 = source.Field2
newBO.Field3 = source.Field3
etc.

The nice thing about this method is that I get total control over which fields from the source BO get brought into the new BO. I can also set things like userkey based on the currentUser's key value.

Or I can conditionally change values if the conditions warrant it.

Joe

Sarosh replied on Wednesday, June 27, 2007

Hi!

I guess that would work too, but in our case we have lots of columns/properties and to manually add them is PIA plus if you add new cols/props then we have to remember to go back and update this method too.

Maybe a better option is add an Attribute <Duplicatable> (if there is such a word) to the properties that you want to be able to duplicate and then the Duplicate method loops through all props with that Attribute set and does its thing.

Sarosh

Sarosh replied on Wednesday, June 27, 2007

Hi!

I have completed my BO.Duplicate() method in my class and it is working fine but now how do I convert this code into my abstract base class using generics so that all my subclass get this method automatically through inheritance?

Here is the code for the Duplicate method in my Project concrete class:

public ProjectList Duplicate()

{

ProjectList New = ProjectList.NewProjectList();

int IDTemp = New.ID;

New = this.Clone();

New._id = IDTemp;

New.MarkNew();

return New;

}

Copyright (c) Marimer LLC