+ Start a Discussion

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){

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]);

//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!!
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: