X++ Copying a Record

Hi guys. This post is written base on the sample code from well-known recipe 'Copying a record' in Microsoft Dynamics AX 2012 Development Cookbook. However I also show some scenarios we might apply this useful technique.

Simple copying by .data() and buf2Buf()

First, I have table 'SourceA' which looks like as follows:

numberfieldAfieldBfieldC
DLS-1001syambbbccc

I copy the above record by this code.
static void syamCopy(Args _args)
{
    Syam syam1,destination;
                
    
    syam1Syam ::find('DLS-1001');
    
    ttsBegin;
        destination.data(source);     
        destination.number = 'DLS-1002';
        if (!destination.validateWrite())
            throw Exception::Error;
        destination.insert();
    ttsCommit;
    info('done');
}

the result will  looks like this.
numberfieldAfieldBfieldC
DLS-1001syambbbccc
DLS-1002syambbbccc

It can also be done by buf2Buf().
destination.data(source);   --- replace by ---> buf2Buf(source, destination);

The result is exactly same.

Mechanism of buf2buf()

static void buf2Buf(Common _from, Common _to)
{
     DictTable dictTable = new DictTable(_from.TableId);
     FieldId fieldId = dictTable.fieldNext(0);
     while (fieldId && ! isSysId(fieldId))
     {
          _to.(fieldId) = _from.(fieldId);
          fieldId = dictTable.fieldNext(fieldId);
     }
}

From above code, two things buf2Buf() are different to .data() are buf2Buf excludes the system fields and slower than .data() because of individual each fields copying.


Updating by buf2Buf()

We can also reduce the tradition line of code when we update a record by using copy instead. This is useful when we get a record from the other sources, for example we get the data from file and would like to update the new data on the same number.

Before update









Code
static void TestUpdate(Args _args)
{
    SourceA     source,
                destination;

    source.number   = '001';
    source.fieldA   = 'xxx';
    source.fieldB   = 'yyy';
    source.fieldC   = 'zzz';   
    destination     = sourceA::find('001',true);

    ttsBegin;       
        buf2Buf(source, destination);
        if (!destination.validateWrite())
            throw Exception::Error;
        destination.update();
    ttsCommit;
    info('done');
}

After update









We can apply .data() also but not exact above code as .data() include the system fields so it needs to update record before. Therefore when we apply 'Copying' to 'Updating' like this, buf2Buf would be easier to apply.

Thanks for reading. Having a good time!

syam

Comments

Popular posts from this blog