Salesforce 顶点代码在自定义对象中创建重复项

Salesforce apex code creates duplicates in custom object

我有这个顶点批次 class: 下面的 MDU_Squad_Data_min__c 自定义对象在城市和省份列中有很多重复值。 使用下面的代码,我能够在一定程度上借助 contains 方法去除重复项,但仍然存在重复值:

global void execute(Database.BatchableContext BC, List<MDU_Squad_Data_min__c> cities) {                  
        List<sumchans__City_Master__c> cityList = new List<sumchans__City_Master__c>(); 
        List<String> cityProvinceList = new List<String>();
        for(MDU_Squad_Data_min__c c: cities) { 
            String cityprovince; 
            cityprovince = (c.CITY_NAME__c).trim() + (c.PROVINCE_CODE__c).trim();                                           
            if(!cityProvinceList.contains(cityprovince)) { 

                sumchans__City_Master__c city = new sumchans__City_Master__c();
                city.Name = c.CITY_NAME__c;
                city.sumchans__PROVINCE__c = c.PROVINCE_CODE__c; 
                cityList.add(city);
            }
            cityProvinceList.add(cityprovince);
        }        
        Database.SaveResult[] MySaveResult = Database.Insert(cityList, false);

另附上结果:

尝试使用集合而不是列表:

Set<sumchans__City_Master__c> cityList = new Set<sumchans__City_Master__c>();

集合用于创建独特的collections,因此您不会有任何重复。

我会在下面建议,因为List.contains主要用于字符串搜索。
全局无效执行(Database.BatchableContext BC,列出城市){
列表 cityList = new List(); 列出 cityProvinceList = new List();
对于(MDU_Squad_Data_min__c c:城市) { 字符串城市省; cityprovince = TRIM(c.CITY_NAME__c) + TRIM(c.PROVINCE_CODE__c);

    if(!cityProvinceList.contains(cityprovince)) { 

        sumchans__City_Master__c city = new sumchans__City_Master__c();
        city.Name = c.CITY_NAME__c;
        city.sumchans__PROVINCE__c = c.PROVINCE_CODE__c; 
        cityList.add(city);
                                                  }
   cityProvinceList.add(cityprovince); 
}
Database.SaveResult[] MySaveResult = Database.Insert(cityList, false);

}

您正在使用一个对象执行 list.contains,因为每次找不到匹配项时您都在创建新对象。

 global void execute(Database.BatchableContext BC, List<MDU_Squad_Data_min__c> cities) {  
List<sumchans__City_Master__c> cityList = new List<sumchans__City_Master__c>();  
Set<String> cityNames = new Set<String>();     
for(MDU_Squad_Data_min__c c: cities)
{
   if(!cityNames.contains(c.City_Name__c))
   {
     sumchans__City_Master__c city = new sumchans__City_Master__c();
     city.Name = c.CITY_NAME__c;
     city.sumchans__PROVINCE__c = c.PROVINCE_CODE__c; 
     cityList.add(city);
     cityNames.add(city.CITY_NAME__c); 
   }
}
Database.SaveResult[] MySaveResult = Database.Insert(cityList, false);

}

这就是我们所需要的。我现在得到了预期的结果。我只需要将第二个参数的值设置为比记录总数更高的值。

cityMduMaster c = new cityMduMaster();
database.executeBatch(c,5000000);

正如您所指出的,这可能是快速解决方法,即给定一个比记录总数更高的参数值,就可以达到预期的结果。