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?).