// Register this in PRE-UPDATE of EntityA, set FILTERING ATTRIBUTES to only include "NAME" field.
// UPPER-CASE STRINGS NEED TO BE REPLACED WITH THE CORRECT NAMES OF ENTITIES AND FIELDS
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
// grab EntityA record being updated
var entityA_Record = context.InputParameters["Target"] as Entity ?? throw new InvalidPluginExecutionException("Target");
// grab the content of "Name" field
var entityB_reference = entityA_Record.GetAttributeValue<EntityReference>("ENTITYA_NAME");
// if "Name" is empty, clear "Id"
if(entityB_reference == null)
{
entityA_Record["ENTITYA_ID"] = null;
}
else
{
// if "Name" is not empty, grab the EntityB record and put "CaseId" in "Id"
var entityB_record = service.Retrieve(entityB_reference.LogicalName, entityB_reference.Id, new ColumnSet("CASEID"));
var caseId = entityB_record.GetAttributeValue<string>("CASEID");
entityA_Record["ENTITYA_ID"] = caseId;
}
// I can't remember if the following line is needed
// put back the data of EntityA where you got it to make it so the fields are updated properly
context.InputParameters["Target"] = entityA_Record;
}
Note that in recent versions of CRM this can be achieved by out-of-the-box calculated fields, I'd consider upgrading.