src/_Internals/ConvertTo-XrmSyncRecordInternal.ps1
|
<# Build the record that Sync-XrmRecords upserts on the target from a source entity, with its state and status apart. statecode, statuscode and createdon are governed by StateHandling and PreserveCreatedOn, whatever ExcludedAttributes says (the default list holds them because they cannot be written directly): their values are kept here even when excluded (H9). createdon goes to overriddencreatedon, which is only valid on create: the platform applies it when the upsert creates the record and ignores it, without error, when the upsert updates it (checked 2026-12-04), so it is always sent (H10). Returns { Record = Entity; StateCode = int or $null; StatusCode = int or $null }. #> function ConvertTo-XrmSyncRecordInternal { param( [Parameter(Mandatory = $true)] [Microsoft.Xrm.Sdk.Entity] $SourceEntity, [Parameter(Mandatory = $false)] [String[]] $ExcludedAttributes = @(), # Columns of the target table [Parameter(Mandatory = $true)] [System.Collections.Generic.HashSet[string]] $TargetAttributes, # Columns of the target table that are valid for update [Parameter(Mandatory = $true)] [System.Collections.Generic.HashSet[string]] $UpdatableAttributes, [Parameter(Mandatory = $false)] [bool] $IncludeEntityReferences = $false, [Parameter(Mandatory = $false)] [bool] $PreserveCreatedOn = $true ) $stateCode = $null; $statusCode = $null; $attributes = @{}; foreach ($sourceAttribute in $SourceEntity.Attributes.GetEnumerator()) { $attributeName = [string]$sourceAttribute.Key; $attributeValue = $sourceAttribute.Value; if ($attributeName -eq "statecode") { if ($attributeValue) { $stateCode = $attributeValue.Value; } continue; } if ($attributeName -eq "statuscode") { if ($attributeValue) { $statusCode = $attributeValue.Value; } continue; } if ($attributeName -eq "createdon") { if ($PreserveCreatedOn -and $null -ne $attributeValue -and $TargetAttributes.Contains("overriddencreatedon") -and $ExcludedAttributes -notcontains "overriddencreatedon") { $attributes["overriddencreatedon"] = $attributeValue; } continue; } if ($ExcludedAttributes -contains $attributeName) { continue; } if ($attributeValue -is [Microsoft.Xrm.Sdk.EntityReference] -and -not $IncludeEntityReferences) { continue; } if (-not $TargetAttributes.Contains($attributeName) -or -not $UpdatableAttributes.Contains($attributeName)) { continue; } $attributes[$attributeName] = $attributeValue; } [PSCustomObject]@{ Record = New-XrmEntity -LogicalName $SourceEntity.LogicalName -Id $SourceEntity.Id -Attributes $attributes; StateCode = $stateCode; StatusCode = $statusCode; }; } |