The transaction must be disposed before the connection can be used to execute SQL statements

I am doing an “EndActivity” from MES. Setup a Data Directive (In-Transaction) to generate a lot number, rather than using the default job as the lot number. Below is the code. I am getting the error “The transaction associated with the current connection has completed but has not been disposed. The transaction must be disposed before the connection can be used to execute SQL statements.”

The code works on a job where there is only one backflush material, but when there are more than one, I get the error. I can see the PartTran Data Directive being run for each material, but really I only need it to run once for the job with the “MFG-STK” trantype. I have tried putting that in there, but it still runs each time for each material. Is there any other better way to do this? Thanks.

//check if the company config checkbox for use JobNum as LotNum is checked.  If not checked, we can do this */
if(!Db.XbSyst.Where(c => c.Company == Session.CompanyID).Select(c => c.JobLotDflt).FirstOrDefault())
{
  foreach(var r in ttPartTran.Where(r => r.RowMod == "U" || r.RowMod == "A"))
  {
    //looks at the current lotnum in the record. 
    //the transaction creates the parttran row first, then updates it.
    //only fire this when a lotnum is present so (1) the empty row is not affected (2) if the part is not lot tracked we don't need to do anything
    if(!string.IsNullOrEmpty(r.LotNum) && r.JobNum == r.LotNum && r.InventoryTrans == true)
    {
      using(var lotSvc = Ice.Assemblies.ServiceRenderer.GetService<Erp.Contracts.LotSelectUpdateSvcContract>(Db))
      {
        if(r.TranQty > 0)
        {
          string newLotNum;          
          lotSvc.GenerateNewLotNum(r.PartNum, out newLotNum);
          r.LotNum = newLotNum;
          PartLot p = new PartLot();          
          p.PartLotDescription = $"{r.TranReference}";
          p.PartLotDescription = p.PartLotDescription.Length > 30 ? p.PartLotDescription.Substring(0,30) : p.PartLotDescription;
          p.Company = r.Company;
          p.PartNum = r.PartNum;
          p.LotNum = r.LotNum;
          p.FirstRefDate = DateTime.Now;
          p.OnHand = true;
          Db.PartLot.Insert(p);
          Db.Validate();  
    
        }//if tranqty > 0        
      }//using lot service
    }//if jobnum == lotnum  
  }//foreach added and updated row
}//if company config use job as lot