How to select the primary address in Ax 2009?

How to select the primary address of a Customer/Vendor/Employee?

In MS dynamics Ax 2009 address architecture, every cataloged person can have many addresses attached to it, with different types such as invoice, delivery, business and so on, usually one of these addresses is set to primary.

CustTable Primary Address
CustTable Primary Address

The primary information is placed in DirPartyAddressRelationship Table. This solution consists on creating a new method in the Address table, which selects the primary address according to the field “isPrimary” in DirPartyAddressRelationship.

To do so, you’re gonna have to create a new find method in Address Table, check the code:

//<AxaptaHut>
public static Address findPrimary(
  tableId     _tableId,
  recId       _recId,
  boolean     _update = false)
{
  Address  address;
  DirpartyAddressRelationshipMapping mapping;
  DirPartyAddressRelationship relationship

  if (_tableId && _recId)
  {
    address.selectForUpdate(_update);

    select firstonly address
      where address.AddrRecId == _recId
      join mapping
        where address.dataAreaId == mapping.RefCompanyId
           && address.RecId == mapping.AddressRecId
           join relationship
            where relationship.RecId == mapping.PartyAddressRelationshipRecId
               && relationship.IsPrimary == Noyes::Yes;
  }
  return address;
}
//</AxaptaHut>

To consume this method you’ll need to do something like this:

//<AxaptaHut>
static void FindPrimaryAddress(Args _args)
{
  Address         addrPrimary;
  DirPartyTable   dirPartyTable;

  dirPartyTable = dirPartyTable::find(CustTable::find("0002").PartyId);
  addrPrimary = address::findPrimary(dirPartyTable.TableId,dirPartyTable.RecId);
  info(addrPrimary.Name);
}
//</AxaptaHut>

Hope it has been usefull.

Felipe Nogueira.