D365FO – AX – Import CSV file into a Table with RecordInsertList for best DB insert performance

static void ImportWithStreamReader(Args _args)
{
   //Declarations
   Filename                filename = @'C:\file.txt';
   System.IO.StreamReader  reader;
   System.String           line;
   InteropPermission       interopPermission;
   container               con;
   str                     itemId;
   str                     startDate;
   str                     qty;
   str                     inventDimId;
   str                     modelId = 'NIC';
   InventDimId             inventDimIdDefault = 'XXX-000614941';
   ForecastSales           forecastSales;
   ForecastInvent          forecastInvent;
   RecordInsertList        insertListForecastSales = new RecordInsertList(ForecastSales.TableId);
   RecordInsertList        insertListForecastInvent = new RecordInsertList(ForecastInvent.TableId);
   int                     recordsCurrentlyInsertedForecastSales, recordsCurrentlyInsertedForecastInvent;
 
   interopPermission = new InteropPermission(InteropKind::ClrInterop);
   interopPermission.assert();
 
   reader = new System.IO.StreamReader(filename,
                                      System.Text.Encoding::get_UTF8());
   //First line is the header
   line = reader.ReadLine();
 
   while (!System.String::IsNullOrEmpty(line))
   {
       line = reader.ReadLine();
       if (!line)
       {
           break;  
       }
       con = str2con(line,';');
       itemId      = conpeek(con,1);
       startDate   = conpeek(con,2);
       qty         = conpeek(con,3);
       inventDimId = inventDimIdDefault;
 
       //Insert records into ForecastSales
       forecastSales.ItemId = itemId;
       forecastSales.StartDate = str2Date(startDate, 123);
       forecastSales.ModelId = modelId;
       forecastSales.InventDimId = inventDimId;
       recordsCurrentlyInsertedForecastSales = insertListForecastSales.add(forecastSales);
       //Insert records into ForecastInvent
       forecastInvent.ItemId = itemId;
       forecastInvent.DateBudget = str2Date(startDate, 123);
       forecastInvent.ModelId = modelId;
       forecastInvent.InventDimId = inventDimId;
       recordsCurrentlyInsertedForecastInvent = insertListForecastInvent.add(forecastInvent);
   }
 
   //Confirm saving records into DB
   recordsCurrentlyInsertedForecastSales = insertListForecastSales.insertDatabase();
   recordsCurrentlyInsertedForecastInvent = insertListForecastInvent.insertDatabase();
 
 
   reader.Close();
   reader.Dispose();
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s