function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
amyer2240amyer2240 

Duplicate Value error on change set

I have a trigger & test that work fine in my sandbox but when I try to deploy I get the following error:
DUPLICATE_VALUE, duplicate value found: Space_Key__c duplicates on record with id: [id for a space record]

Here is the trigger that's causing this error:

trigger Assignment on Account (after insert) {

//soft-coding space id
List<Space__c> spaces = [Select Name, Id from Space__c];
Map<String, String> spacemap = new Map<String, String>{};
for(Space__c cm: spaces)
spacemap.put(cm.Name, cm.Id);

Space_Account__c newrel = new Space_Account__c ();
for(Account accs : trigger.new){
if(accs.Space_Hidden__c==0)
{

newrel.Space__c = spacemap.get('National');
newrel.Account__c = accs.Id;

//here I tried to query to see if there was already an account key - i didnt get the systemdebug message so I dont think there was
set <Space_Account__c> setkey = new Set <Space_Account__c> ([select Space_Account_Key__c from Space_Account__c where Id =:newrel.Id]);
if(setkey.isEmpty()){

//here I tried to add the +1 to make it unique, but no luck
newrel.Space_Account_Key__c = spacemap.get('National')+cons.Id+1;
}
else {
    System.debug('I contain an account key');
    }

}
upsert newrel;

}}

I really am at a loss about how to avoid the duplicate value error!! Thank you!!
Hargobind_SinghHargobind_Singh
I would suggest re-writing your trigger, as you are executing a DML statement inside FOR statement. Re-writing and testing on Sandbox first might resolve your problem. If it doesn't, then please post your new trigger code. Some information on best-practices here: 

https://developer.salesforce.com/page/Apex_Code_Best_Practices