我在插入触发器执行的新记录时收到此错误:
“System.ListException:在Insert或Upsert列表之前,必须没有两个完全相同的元素”
以下是触发器:
trigger createCETAccount on Account (before update) {
//trigger runs after the update of an Account record
//create a set of all the unique Account IDs
Set<id> AIds = new Set<id>();
//for each instance of the trigger being fired if the Contact field is not blank
//and the Contact Exact Target Send field is not blank and has changed from what it was previously - add that record's ID to the MTIds Set
for (Integer i = 0; i < Trigger.new.size(); i++)
{
if(Trigger.new[i].Contact_Exact_Target_Send__c != Trigger.old[i].Contact_Exact_Target_Send__c && Trigger.new[i].Contact_Exact_Target_Send__c != null)
{
AIds.add(Trigger.new[i].Id);
}
}
//query for all the Account records for the unique AIds in the records
List <Account> aList = new List<Account> ([Select Id, Contact_Exact_Target_Send__c from Account where Id in :AIds]);
//List all the Contacts associated with the Account
List <Contact> ContactList = new List <Contact> ([Select Id, AccountId, isPrimary__c from Contact where AccountId in :AIds ORDER BY isPrimary__c ASC, createdDate DESC]);
//Create a list of ContactExactTarget records
List <ContactExactTarget__c> CETList = new List<ContactExactTarget__c> ([Select ID, Account__c from ContactExactTarget__c where Account__c in :AIds]);
List <ContactExactTarget__c> CETList2 = new List<ContactExactTarget__c>;
//iterate over the list of Account records being processed in the trigger
for(Account acc: aList){
//create a new ContactExactTarget send record for each instance
ContactExactTarget__c objCET = new ContactExactTarget__c();
objCET.ET_Code__c = acc.Contact_Exact_Target_Send__c;
objCET.Account__c = acc.Id;
//add the record to the CETList defined above
CETList.add(objCET);
}
//add the related Contact to the CET record
for(Contact con : ContactList) {
for (ContactExactTarget__c cet : CETList){
if (con.AccountId == cet.Account__c)
cet.Contact__c = con.Id;
CETList2.add(cet);
}
}
//upsert the list to insert the new records
upsert CETList2;
}