+ Start a Discussion
Richie DRichie D 

Adding a child record to a relationship list

Dear all,


Can anybody explain to what the contact 'me' is added to in the code below?

Account a = [select id, name ,(select id, name from Contacts) from Account limit 1];
Contact me= new contact(lastname='smith', firstName='bob', accountId=a.Id);

 Both system.debug statements will show the same records before and after adding me to the collection. Presuming that the collection 'Contacts' is somehow a read-only list; no error is found when running. So, has the add method call been ignored or just somehow adding to the 'wrong collection'...


This isn't a problem that needs fixing but may get you wondering like me ;)





List of all contacts under the account are retrieved




This particular contact has been added to existing list of contacts of that particular account


You have to insert the contact record first, for certain.  If you then add it to a.contacts it might work, but I think you will have to re-query the account.


Yeah, you're only adding it to the Contacts list that's in memory, not in the DB.