Friday, October 22, 2010

Rename a Primary Key in AX through code

In this post, I am going to discuss about how to rename a primary key in AX. The renaming can be done for any record using the CCPrimaryKey Class. Let us suppose, if Customer Id 1000 has to be renamed as Cust_1000 then it will be renamed in all the tables(SalesTable, CustTable, SalesQuotationTable etc.,) wherever this cutomer Id has been used. The generic way to rename a primary key for any table is as follows:

Send a record to this method as a parameter.

void renamePrimaryKey(Common _common)
{
Common common;
FieldId fieldId;
DictTable dictTable;
DictField dictField;
;
common = _common;
dictTable = new SysDictTable(common.TableId);
dictField = new SysDictField(dictTable.id(), dictTable.primaryKeyField());

if (isConfigurationkeyEnabled(configurationkeynum(SIG)))
{
SIGBaseDocument::checkAndCacheRename(common,dictField.id(),newValue);
}

startLengthyOperation();
fieldId = dictField.id();
try
{
ttsbegin;

// CC Start
CCPrimaryKey::renamePrimaryKey(common, dialogField.value(), fieldId);
// CC End

common.(fieldId) = dialogField.value();

common.renamePrimaryKey();
if (common.TableId == tablenum(UserInfo))
{
common.update();
}
ttscommit;
}
catch (Exception::Error)
{
ttsabort;
}

}

No comments: