I'm trying to make something that reads csv's and imports the data for our users, but SF ids for the lookups on the Contact are cumbersome for them as they already know the External Ids of the object related.
For Example:
We have a Country_of_Domicile__c object which has an external Id which might be for example 'USA' or 'ENG'.
The Contact has a lookup to this object on the Country_of_Domicile__c field.
How can I, only knowing the external ID of the record, attach it to the contact that is being Upserted.
Example non-working code below of what i'm trying to achieve:
string relatedObjectName = 'Country_of_Domicile__c';
sObject relatedsObj = Schema.getGlobalDescribe().get(relatedObjectName ).newSObject();
relatedsObj.put('External_Id__c','ENG');
contact.putSObject(fieldName,relatedsObj);
Obviously I know i can query for this data and use a Map to put the ID directly but i'd rather not given then limits and loops, and also not knowing how many queries i'll need at run-time. Is this possible without any Queries?
The above doc says what i'm trying to do should be more-or-less possible but it explicitly declares the type of the Object and again I'd like to be able to avoid that to have it more flexible.
Edit: Marking Adrian's answer as correct as it was accurate I just want to add the following block of code that is hopefully a bit more generic:
string relatedObjectR = 'COD__r'; //field name on contact that looks up country with the __c replaced with __r
string relatedObjectC = 'Country_of_Domicile__c' //object name
string extIdField = 'Code__c' // External Id field on the related object
string data = 'ENG'; //Country's external Id
sObject relatedsObj = Schema.getGlobalDescribe().get(relatedObjectC).newSObject(); //instantiates lookup object
relatedsObj.put(extIdField,data); //sets the External Id of that object
contact.putSObject(relatedObjectR, relatedsObj); //puts the value onto the correct field on the contact: 'COD_c'