Wednesday, August 20, 2014

Unit Of Work Implementation in Dynamics AX

Unit of Work is a new framework , which is being introduced in AX 2012.
It is use to commit number of records in a single Transaction.The main reason for introducing unit of work is that it is impossible to insert the lines table record before its header table  because there is a relation between the header table and the lines table.The Recid of the header table is comes as a foreign key in the child table.

Now we dont have to hold the recid of parent table and also we can insert all data in a single trip . How., Let us Implement this :

  1. Create 2 table SKUHeader and SKULine.
  2. SKULine is related to SKUHeader by RecId.
  3. Go to relation of table and make sure property CreateNavigationPropertyMethods = True by making this property true , system will add appropriate methods to table SKULine
  4. create a class as shown blow.
         public class SKUUnitOfWork
            {
               }
         
          5. Now create a method, remember UnitofWork will always used on server
      public server static void main(Args args)
      {
          SKUHeader                      skuHeader;
          SKULine                        skuLine;

          int                            mycount;
          int                            mycount2;

          UnitofWork unitofWork = new UnitofWork();

          for(mycount=0; mycount<10; mycount++)
          {
           //insert data in parent table
              skuHeader.clear();
              skuHeader.GroupName = 'ProductGroup_' + int2str(mycount+1);
              unitofWork.insertonSaveChanges(skuHeader);

              for(mycount2=0; mycount2<10; mycount2++)
              {
                  //insert data in child table
                  skuLine.clear();
                  skuLine.ProductName = 'Product_' + int2str(mycount2+1);
                  skuLine.ProductPrice = int2str(mycount2+1 * 5);
                  skuLine.SKUHeader(skuHeader);
                  unitofWork.insertonSaveChanges(skuLine);
              }
          }
          //Now insert data in a single trip
          unitofWork.saveChanges();

          info('Done');
      }


          6. Finally generate a action type menuItem for SKUUnitOfWork class.

      you have done. as you will execute menuItem it will call the main method of the class.
      see complete snapshot.





      1 comment: