Copying entities from one collection to another

Posts   
 
    
tprohas
User
Posts: 257
Joined: 23-Mar-2004
# Posted on: 10-Nov-2005 20:18:18   

Can anyone tell me why when running this code the wheelItem that is being added to the build.BuildItem collection is somehow removed from the WheelBuild.BuildItem collection at the same time. This is throwing an error saying the WheelBuild.BuildItem collection has changed when I'm not trying to change it.

foreach(BuildItemEntity wheelItem in WheelBuild.BuildItem)
                this.build.BuildItem.Add(wheelItem);
bclubb
User
Posts: 934
Joined: 12-Feb-2004
# Posted on: 11-Nov-2005 02:54:46   

This piece of code is throwing the error? Can you post a little more about how both collections are created? Thanks

Paul.Lewis
User
Posts: 147
Joined: 22-Aug-2005
# Posted on: 11-Nov-2005 04:47:05   

An entity can only exist in one collection at a time.

Cloning the wheelItem entity and adding it to the destination collection should resolve your issue.

foreach(BuildItemEntity wheelItem in WheelBuild.BuildItem)
{
   BuildItemEntity clone = new BuildItemEntity();
   clone.Fields = ((EntityFields2)wheelItem .Fields).Clone();
   this.build.BuildItem.Add(clone);
}
tprohas
User
Posts: 257
Joined: 23-Mar-2004
# Posted on: 11-Nov-2005 19:04:37   

This did fix my problem, but I had to make a small adjustment to the code as it was also giving me an error. The following code works, thank you for the help.

The method Clone() returns an object which has to be cast back to IEntityFields2.

foreach(BuildItemEntity wheelItem in WheelBuild.BuildItem)
{
    BuildItemEntity newWheelItem = new BuildItemEntity();
    newWheelItem.Fields = (IEntityFields2)((EntityFields2)wheelItem.Fields).Clone();
    build.BuildItem.Add(newWheelItem);
}