I am new to Apex, and stuck at a very basic thing. I have 3 objects. Contract, Site Opportunity, and Sites. (last 2 with lookup with Contract). Opportunity is above contract. I want to check how many Site Opportunity are there, and i want to copy them to Sites using a button on Opportunity. But my button is entering duplicate records everytime its clicked. Here is the code:
Contract__c OppContract = [select id from contract__c where Ren_Opportunity__c =: RenOpptyId and Con_Stage__c = 'Executed' ] ; // RenOpptyId is passed on the method
list<ConSite__c> ListCSite = new list<ConSite__c>([select id, Site__c, Deals__r.Contract__c, Deals__r.Contract__r.Opportunity__c, Deals__r.ContractV2__r.Ren_Opportunity__c
from ConSite__c
where Deal__r.Contract__c =:OppContract.id]);
list<Site_Opp__c> SiteOpp = new list<Site_Opp__c>select id, site__c, Opportunity__c from Site_Opp__c where Opportunity__c =: RenOpptyId
List<Site_Opportunity__c> ListSiteOpp =new List<Site_Opportunity__c>();
system.debug('OppContract=' +OppContract);
system.debug('ListCSite=' +ListCSite);
for(ConSite__c CS:ListCSite)
{
// HERE I WANT TO COMPARE ListCSite.SITE__C != SiteOpp.Site__C, if true then copy the site from Consite and paste it in SiteOpportinty
if(!string.isEmpty(CS.Deals__r.Contract__r.Ren_Opportunity__c))
{
Site_Opportunity__c NewSiteOpp = new Site_Opportunity__c();
NewSiteOpp.Opportunity__c = CS.Deals__r.Contract__r.Ren_Opportunity__c;
NewSiteOpp.Site__c = CS.Site__c;
ListSiteOpp.add(NewSiteOpp);
system.debug('ListSiteOpp=' +ListSiteOpp);
}
}
insert ListSiteOpp;