UID_SAPGrpDefault Column Template Issue

Below is the template I am using to automatically calculate the value for UID_SAPGrpDefault.

#If ORG Then
#End If

dim f as ISqlFormatter = Session.SqlFormatter
dim termName as String = Session.Config.GetConfigParm(String.Format("Custom\SAP\UserGroup\Termination"))
dim AccountDef as IEntity = Session.Source.Get(New DbObjectKey($FK(UID_TSBAccountDef).ObjectKeyTargetSystem$))

If CBool(Connection.Variables.Get("FULLSYNC")) = False and $FK(UID_Person).IsInactive:bool$ = True Then
	Value = Session.Source.GetSingleValue(Of String)(Query.From("SAPGrp").Where( f.AndRelation( _
																		f.Comparison("UID_SAPMandant", AccountDef.GetValue("UID_SAPMandant").String, ValType.String, CompareOperator.Equal), _
																		f.Comparison("Name", termName, ValType.String, CompareOperator.Equal))) _
End If

If CBool(Connection.Variables.Get("FULLSYNC")) = False and $FK(UID_Person).IsInactive:bool$ = False Then
Select Case ($FK(UID_TSBBehavior).ITDataUsage:Int$)
	Case 0:'do not get data from employee
	Case -1:'fill property initially from the ITData of the employee
		If Not $[IsLoaded]:Bool$ Then
			Value = TSB_ITDataFromOrg($UID_Person$, $UID_TSBAccountDef$, Base.TableDef.Columns("UID_SAPGrpDefault")) 
		End If
	Case 1:'update property depending on ITData of the employee
		Value = TSB_ITDataFromOrg($UID_Person$, $UID_TSBAccountDef$, Base.TableDef.Columns("UID_SAPGrpDefault")) 
End Select
End If

However, when assigning the account definition to a user, the SAP_PersonHasTSBAccountDef_Autocreate_SAPUser fails. The code does work if the account already exists. I have narrowed the issue down to the top half where if checks to see if the Person record value for IsInactive = TRUE but I am not sure what is wrong with it. Below is the error I get on the process when it runs.

ErrorMessages (2020-06-11 14:31:05.050) [810306] Error during execution of 'SetValues' in logic module 'VI.DB.Entities.EntityScriptLogic'.
[810126] SAP user accounts: Error applying dynamic template for User group on object ().
[810222] Error executing script 'Tmpl_SAPUser_UID_SAPGrpDefault'.
[810353] Cannot get object with empty key.