+ Start a Discussion
SFDC 18SFDC 18 

Error: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Zone__c.Name__c

Hi 

I got this error when i tried to execute the below code in anonymous window
 
public class NoofMaleAgents {
    
    public NoofMaleAgents(){
        
        for(zone__c z : [SELECT Id,No_of_Male_Agents__C FROM Zone__C]){
            
            z.No_of_Male_Agents__C = [SELECT count() FROM Agent__C WHERE Gender__C =: 'Male' AND Zones__C =: z.Name__C ];
            
            upsert z;
        
    }
        for(zone__c z : [SELECT Id,No_of_Female_Agents__C FROM Zone__C]){
            
            z.No_of_Female_Agents__C = [SELECT count() FROM Agent__C WHERE Gender__C =: 'Female' AND Zones__C =: z.Name__C];
            
            upsert z;
            
        }

    }
}

 
Best Answer chosen by SFDC 18
Steven NsubugaSteven Nsubuga
Update the zone__c queries to include the Name__c field 
public class NoofMaleAgents {
    
    public NoofMaleAgents(){
        
        for(zone__c z : [SELECT Id, Name__C, No_of_Male_Agents__C FROM Zone__C]){
            
            z.No_of_Male_Agents__C = [SELECT count() FROM Agent__C WHERE Gender__C =: 'Male' AND Zones__C =: z.Name__C ];
            
            upsert z;
        
    }
        for(zone__c z : [SELECT Id, Name__C, No_of_Female_Agents__C FROM Zone__C]){
            
            z.No_of_Female_Agents__C = [SELECT count() FROM Agent__C WHERE Gender__C =: 'Female' AND Zones__C =: z.Name__C];
            
            upsert z;
            
        }

    }
}

 

All Answers

Steven NsubugaSteven Nsubuga
Update the zone__c queries to include the Name__c field 
public class NoofMaleAgents {
    
    public NoofMaleAgents(){
        
        for(zone__c z : [SELECT Id, Name__C, No_of_Male_Agents__C FROM Zone__C]){
            
            z.No_of_Male_Agents__C = [SELECT count() FROM Agent__C WHERE Gender__C =: 'Male' AND Zones__C =: z.Name__C ];
            
            upsert z;
        
    }
        for(zone__c z : [SELECT Id, Name__C, No_of_Female_Agents__C FROM Zone__C]){
            
            z.No_of_Female_Agents__C = [SELECT count() FROM Agent__C WHERE Gender__C =: 'Female' AND Zones__C =: z.Name__C];
            
            upsert z;
            
        }

    }
}

 
This was selected as the best answer
SFDC 18SFDC 18
Thank You. Its working now
Steven NsubugaSteven Nsubuga
You're welcome!