+ Start a Discussion
Robert WynterRobert Wynter 

I'm hitting our soql limit when I added new code

I've tweaked an unmanaged package to include an additional Affiliation upsert and it's causing my limit to exceed. if someone can please suggest what I can do to fix the following I would appreciate it. I'm only just learning this stuff. Thank you in advance :)
public void processInteractions(List<Interaction__c> newInteractions) {
	List<hed__Affiliation__c> affiliationsToUpsertagent = new List<hed__Affiliation__c>();

            //added Agent Affiliation on Agent_Key__c

   if (interaction.Affiliated_Agent_Account__c != null) {

       // Upsert Affiliations using the Upsert_Agent_Key__c
   if (affiliationsToUpsertagent.size() > 0) {
	logPossibleErrors(Database.upsert(affiliationsToUpsertagent, hed__Affiliation__c.Upsert_Agent_Key__c, false));


We want to inject Apex directly into the SOQL query itself!
What we want to do is create a bind variable. A “bind variable” is simply the term for an Apex variable used inside a SOQL query.
Salesforce knows you’re using a bind variable when you precede your Apex variable with a colon (:)
1. we set the string variables for Contact and Agent Account ID's
2. Then, in our SOQL query, we used a bind variable to find every Affiliation Account in our database that has the same Contact with Agent to see if it exists!
3. if it does NOT exists, we insert the agent Affiliation

private hed__Affiliation__c createAgentUpsertAffilFromInteraction(Interaction__c interaction) {
//Set String Variables
        String checkConID =interaction.Contact__c;
        //String checkAccID =interaction.Agent_Key__c;
        String checkAccID =interaction.Affiliated_Agent_Account__c;
        //Use SOQL query with Bind Variables to check for Existing Agent Account on Contact
        List<hed__Affiliation__c> AllAccounts= [select id, name 
                                FROM hed__Affiliation__c  
                                WHERE hed__Account__c= :checkAccID AND hed__Contact__c= :checkConID]; 
        //Set a list Affiliation for upsert

         hed__Affiliation__c newAffil1 = new hed__Affiliation__c();
        // intMappingService.applyDataToSObject(interaction, newAffil1); 
        if(AllAccounts.size() ==  0)//if affilisation does NOT already exisits, then create new affiliaition on Contact
        intMappingService.applyDataToSObject(interaction, newAffil1);//set up mapping for affiliation

        newAffil1.Upsert_Agent_Key__c = interaction.Contact__c + '.' + interaction.Affiliated_Agent_Account__c;
        newAffil1.Upsert_Key__c = interaction.Contact__c + '.' + interaction.Affiliated_Agent_Account__c;// because of the same mapping being used for the first affiliation record we need to replace it with agent
        newAffil1.hed__Account__c=  interaction.Affiliated_Agent_Account__c;


        upsert newAffil1;
        return newAffil1;