Question:
Salesforce allows me to write specific field values to specific related list records on an object in a Map by referencing the __r[Index] relationship of that particular record.
However, it does not allow me to overwrite the entire Related List in memory with a new (or modified) list of the same SObject Type. Why?
Example (Not Writeable):
Map<Id,SObject1> objectMap = new Map<Id,SObject1>([SELECT Id,
(SELECT Id,Field_Name__c FROM SObjects2__r)
FROM SObject1]);
if(objectMap.containsKey(objectId)){
SObject1 object1 = objectMap.get(objectId);
List<SObject2> new2List = new List<SObject2>();
object1.SObjects2__r = new2List; // Not writeable
}
Example (Writeable):
Map<Id,SObject1> objectMap = new Map<Id,SObject1>([SELECT Id,
(SELECT Id,Field_Name__c FROM SObjects2__r)
FROM SObject1]);
if(objectMap.containsKey(objectId)){
SObject1 object1 = objectMap.get(objectId);
object1.SObjects2__r[0].Field_Name__c = 'Field Value'; // Writeable
}