I have a CRM custom plugin that is registered (via CRM Plugin Registration Tool) on the event Create Job. 'Create' being the message and 'job' being the Primary Entity.
Upon creation of a new job, I want to take that entity and automatically assign it a project number. I always set the 'Event Pipeline Stage of Execution' to be Post-Operation. I have tried both Execution Modes (Asynchronous and Synchronous).
Asynchronous always throws me an error along the lines of "Entity job with ID '' does not exist"
Synchronous never throws an error but none of the code within my tool is being performed.
public void Execute(IServiceProvider serviceProvider)
{
var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var orgService = factory.CreateOrganizationService(null);
var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
Entity ent = (Entity)context.InputParameters["Target"];
IOrganizationService service = factory.CreateOrganizationService(null);
if (ent.LogicalName == "cmc_job")
{
try
{
ent["cmc_jobnumber"] = "0000001";
ent["cmc_name"] += " - DEMO";
service.Update(ent);
}
catch (Exception e)
{
Console.Write(e.Message);
}
}
I have also tried service.Create(entity) as well but I tend to run into errors with that as well. These errors often relate to having duplicate records. Also I have made sure to deactivate any existing processes that relate to creating jobs.
How can I properly update an entity field immediately after creating the entity? Which practice is best?
Side Note: The reason I am deciding to use a CRM Custom Plugin and not a custom Processes is because I need to query out the largest existing project number and then adding 1 to it.