Monday, December 15, 2014

Unit of Work

After the post about surrogate keys I was asked the following question:
There is the following problem with using surrogate keys.
A record gets RecId value at the moment it is inserted into the database. What if we are doing bulk insert of a journal with many lines and the journal header contains some totals calculated based on its lines. It is impossible to insert lines before header since the value of the journal's surrogate key is unknown. But that would be so convenient because otherwise the header should be inserted first, then the lines and then the header should be updated with the calculated totals.


The answer is – use Unit of Work. It allows to perform create, update and delete operations without worrying about the order of those and without a need to specify surrogate key values. It will all be done automatically in the kernel!

Example:
Let we have the following tables:


The following job will insert the journal header with calculated totals and 10 lines. Note, that there is no place where surrogate keys are mentioned in the code. Business data only.


And here is the result.



Some more details about the unit of work feature:
  1. All database operations happen only when saveChanges() method is invoked.
  2. UnitOfWork class has insertOnSaveChanges(), updateOnSaveChanges() and deleteOnSaveChanges() methods for CUD operations.
  3. Surrogate keys can be propagated automatically to related records if buffers are linked via navigation methods (AJournalLine.header() method in the example). Navigation methods can be created automatically from relations. I’ll write a separate post about them.

And the last but not least. AX client has the great support of the unit of work as well. This means that form datasources can be grouped into a unit of work, so all the benefits of simultaneous commit and surrogate key propagation will be available on forms. There are a lot of possibilities and tricks there, so this topic worth one or more dedicated posts as well.

1 comment:

  1. Bet365 casino games - Air Jordan Gaming
    Bet365 bestest air jordan 18 retro yellow suede casino games – sports betting, get air jordan 18 retro yellow live air jordan 18 retro men blue sports casino, and more. All you have to do is where can i find air jordan 18 retro varsity red register how to order air jordan 18 retro men a new account using your chosen account.

    ReplyDelete