D365FO X++ tip for developers: How to solve error insert not allowed for field, when importing data entities

Intro

When creating data entities, sometimes the underlying data source table can have a field that has the Allow Edit On Create property set to No.

In such cases, when trying to import the data entity, we might get one of the following error messages:

Results. insert not allowed for field ‘Invoice source(Invoice Attachment Source Selected)’
Results. Validation of field ‘Invoice source’ failed
Results. Validations failed

Message
Results. insert not allowed for field ‘DocCustAutomationSysEmailSystemTableEntity.InvoiceAttachmentSourceSelected’

The fix

To get around this issue, we first need to set the Allow Edit On Create property of the related field on the data entity itself to Yes.

Secondly, to skip the validation of the underlying data source table, we need to override the peristEntity() method on the data entity and add the following code (NOTE: The call to super() needs to be at the end, otherwise this won’t work!):

public void persistEntity(DataEntityRuntimeContext _entityCtx)
{
    this.skipDataSourceValidateField(fieldNum(DocCustAutomationSysEmailSystemTableEntity, InvoiceAttachmentSourceSelected), true);
    super(_entityCtx);
}

After this fix, the import of the data entity should go smoothly: