Renaming the primary key
Most of you, who are familiar with the Dynamics AX application, have probably used the standard Rename function. This function allows us to rename the primary key of almost any record. It is irreplaceable if a record was saved by mistake or simply needs renaming. The function ensures data consistency that is, all related records are renamed too. It can be accessed from the Record information form (shown in the following screenshot), which can be opened by selecting Record info from the right-click menu on any record:
When it comes to manual mass renaming, this function might be very time-consuming. An alternative way of doing that is to create a job that automatically runs through all required records and calls this function automatically.
This recipe will explain how the record primary key can be renamed through the code. As an example, we will create a job that renames a customer account.
How to do it...
Carry out the following steps in order to complete this recipe:
1. Open Accounts receivable | Common | Customers | All customers and find the account that has to be renamed:
2. Click on Transactions in the action pane to check the existing transactions:
3. Open the AOT, create a new job named
CustAccountRename
, and enter the following code. Use the previously selected account:static void CustAccountRename(Args _args) { CustTable custTable; select firstOnly custTable where custTable.AccountNum == '1103'; if (custTable.RecId) { custTable.AccountNum = '1103_'; custTable.renamePrimaryKey(); } }
4. Run the job and check if the renaming was successful, by navigating to Accounts receivable | Common | Customers | All customers again, and finding the new account. The new account should have retained all its transactions and other related records, as shown in the following screenshot:
5. Click on Transactions in the action pane in order to see if existing transactions are still in place:
How it works...
In this recipe, first we will select the desired customer account that is, 1103. Here we can easily modify the select statement to include more accounts for renaming, but for demonstration purposes, let's keep it simple. Note that only fields belonging to a table's primary key can be renamed in this way.
Then we call the table's renamePrimaryKey()
method, which does the actual renaming. The method finds all the related records for the selected customer account and updates them with the new account. The operation might take a while depending on the volume of data, as the system has to update multiple records located in multiple tables.