【Salesforce】System.ListException: Before Insert or Upsert list must not have two identically equal elements

【Salesforce】System.ListException: Before Insert or Upsert list must not have two identically equal elements

Salesforceでエラーが出たので確認してくださいってなわけで、確認しました。

こんなエラーが発生していました。

System.ListException: Before Insert or Upsert list must not have two identically equal elements

InsertやUpsertするリストに同じ要素を入れてはいけません、とのことです。

そりゃその通りだと思います。

こんなイメージです。

List<Account> accountList;
Account acc1;
Account acc2;

// 取引先1を作成する
acc1 = new Account();
acc1.Name = 'Account1';

// 取引先2を作成する
acc2 = new Account();
acc2.Name = 'Account2';

// 取引先のリストを作成する
accountList = new List<Account>();

// ☆★☆★☆★☆★☆★☆★
// 1つのレコードを2回リストに追加している
accountList.add(acc1);
accountList.add(acc1);

insert accountList;

取引先を2つ作成しているのに、取引先1を2回リストに追加していますね。

もちろん、実際にはもっと複雑な処理で発生していました。

リストに同じレコードを追加しなければ解決です。

List<Account> accountList;
Account acc1;
Account acc2;

// 取引先1を作成する
acc1 = new Account();
acc1.Name = 'Account1';

// 取引先2を作成する
acc2 = new Account();
acc2.Name = 'Account2';

// 取引先のリストを作成する
accountList = new List<Account>();

// ☆★☆★☆★☆★☆★☆★
// 修正済み
accountList.add(acc1);
accountList.add(acc2);

insert accountList;

ループや条件分岐、関数で区切られていると見落とすことがあったりします。

No comments.

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です