0

In Apex is there an efficient way to overwrite an SObject instance with another SObject (both of the same type) without losing parent and children records?

In the following example I want to replace the fields on "record" with those of "cachedRecord" while keeping the related parents and children on the original "record".

// here assume record.Id = cachedRecord.Id
Contact record = getRecord(); // contains parent and related children
Contact cachedRecord = getCachedRecord(); // contains no related records
overwriteRecord(record, cachedRecord); // overwrites fields on record with cachedRecord

I can get the fields on the object, loop through them, and copy them to the source record but this gets inefficient very quick. Alternatively I can use the JSON serializer/deserializer to convert the object to a map, then copy the fields, but again I don't think this is very efficient (or am I wrong?).

1
  • 1
    You could insert the New record, then merge the new and done record via apex. In merge the master record always wins so the values on the new record (master) will remain and relationships will be moved to the new record
    – Eric
    Commented May 5, 2016 at 1:28

2 Answers 2

0

The third option would be to clone the original record (see clone()) and then re-parent all the child records to the cloned record. I think this is a lot more inefficient than copying the field values across. Copying the field values is much more faster than re-parenting records.

0

You could insert the New record, then merge the new and old record via apex. In merge the master record always wins so the values on the new record (master) will remain and relationships will be moved to the new record so:

  1. Insert new record with values
  2. Using Apex Database.merge

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_database.htm#apex_System_Database_merge_2

Merge the records with the new record as the master and the old record as the duplicate

2
  • This is an option but I don't really want to insert SObject instances into the database just for the sake of merging them. Above all it consumes DML calls which is kind of inefficient and slow too. Appreciate the reply tho.
    – Mossi
    Commented May 5, 2016 at 4:20
  • Its may not be any more inefficient than the other options. In addition from a code perspective it is much less complex. Actually I think this is the perfect combination balance simplicity, reliability, and efficiency when compared to the other options. Of course, if you have all sorts of integrations, code, etc that occur due to a record insert and not an update (cause you would have to do that regardless) that could play into the decision
    – Eric
    Commented May 5, 2016 at 4:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .