[SalesForce] External Id upsert

I know that with External Id, I can upsert a record and that will Insert or Update the record base on the External Id (update if exists or insert if not) instead of the regular Id.

Is there is a way to update\ insert a record based on its external Id?

Example (Code__c is an external Id):

List<Example__c> ExampleList= [SELECT Id,Code__c,Name FROM Example__c LIMIT 1]; 
SomeObjectInstance.someLookupField__c = ExampleList[0].Code__c;
insert(SomeObjectInstance);


instead of:
SomeObjectInstance.someLookupField__c = ExampleList[0].Id;
insert(SomeObjectInstance);

What about upsert a related object based on the external Id?

For Example :

Contact con = new Contact();
con.City_Code = getCity('PKR'); // Getcity is the function below

//what should I do now with the contact? 

public static String getCity(String wsDemoCity){
    List<City__c> countryList = [
        SELECT Id,Code__c,City_Name_Eng__c FROM 
        City__c WHERE Code__c =:wsDemoCity LIMIT 1
    ];
    if(countryList.size()>0){  
        return countryList[0].code__c;
    }
}

Best Answer

Instead of insert/update just call upset and specify the external id. The operator will handle it for you.

SomeObjectInstance.someLookupField__c = ExampleList[0].Code__c;
upsert SomeObjectInstance someLookupField__c; 

*Given that someLookupField__c is also an external id field.

Src: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_examples_upsert.htm?search_text=upsert