The Difference Between data() and buf2Buf() in Dynamics AX 2012
Published: September 10, 2020 at 4:31:35 PM UTC
This article explains the differences between the buf2Buf() and data() methods in Dynamics AX 2012, including when it is appropriate to use each and an X++ code example.
The information in this post is based on Dynamics AX 2012 R3. It may or may not be valid for other versions.
When you need to copy the value of all fields from one table buffer to another in Dynamics AX, you would traditionally do something like:
This works well and in most cases is the way to go.
However, you also have the option of using the buf2Buf function instead:
This works well too. So what's the difference?
The difference is that buf2Buf does not copy system fields. System fields include fields such as RecId, TableId, and perhaps most importantly in this context, DataAreaId. The reason the latter is the most important is that the most typical case where you would use buf2Buf() instead of data() is when duplicating records between company accounts, typically by use of the changeCompany keyword.
For example, if you're in the "dat" company and has another company called "com" that you wish to copy all records in CustTable from:
{
buf2Buf(custTableFrom, custTableTo);
custTableTo.insert();
}
In this case, it will work because buf2Buf copies all field values, except system fields to the new buffer. Had you used data() instead, the new record would have been inserted in the "com" company accounts because that value would have been copied to the new buffer as well.
(Actually, it would have resulted in a duplicate key error, but that's not what you want either).